|
23 | 23 | namespace Ninject.Extensions.Factory |
24 | 24 | { |
25 | 25 | using System; |
| 26 | + using System.Linq.Expressions; |
| 27 | + |
26 | 28 | using Castle.DynamicProxy; |
27 | 29 | using Ninject.Activation; |
28 | 30 | using Ninject.Syntax; |
@@ -86,6 +88,37 @@ public static IBindingWhenInNamedWithOrOnSyntax<object> ToFactory(this IBindingT |
86 | 88 | return ToFactory(syntax, ctx => instanceProvider(), factoryType); |
87 | 89 | } |
88 | 90 |
|
| 91 | + /// <summary> |
| 92 | + /// Defines a named binding with the name taken from the factory method used to create instances. |
| 93 | + /// </summary> |
| 94 | + /// <typeparam name="TInterface">The type of the interface.</typeparam> |
| 95 | + /// <typeparam name="TFactory">¨The type of the factory.</typeparam> |
| 96 | + /// <param name="syntax">The syntax.</param> |
| 97 | + /// <param name="action">Expression defining the factory method used to get the binding name from.</param> |
| 98 | + /// <returns> |
| 99 | + /// The <see cref="IBindingWithOrOnSyntax{TInterface}"/> to configure more things for the binding. |
| 100 | + /// </returns> |
| 101 | + public static IBindingWithOrOnSyntax<TInterface> NamedLikeFactoryMethod<TInterface, TFactory>(this IBindingNamedSyntax<TInterface> syntax, Expression<Action<TFactory>> action) |
| 102 | + { |
| 103 | + var methodCallExpression = action.Body as MethodCallExpression; |
| 104 | + |
| 105 | + if (methodCallExpression == null) |
| 106 | + { |
| 107 | + throw new ArgumentException("expected factory method instead of " + action, "action"); |
| 108 | + } |
| 109 | + |
| 110 | + var methodName = methodCallExpression.Method.Name; |
| 111 | + |
| 112 | + if (!methodName.StartsWith("Get")) |
| 113 | + { |
| 114 | + throw new ArgumentException("expected factory 'Get' method instead of " + action, "action"); |
| 115 | + } |
| 116 | + |
| 117 | + var bindingName = methodName.Substring(3); |
| 118 | + |
| 119 | + return syntax.Named(bindingName); |
| 120 | + } |
| 121 | + |
89 | 122 | /// <summary> |
90 | 123 | /// Defines that the interface shall be bound to an automatically created factory proxy. |
91 | 124 | /// </summary> |
|
0 commit comments