Skip to content

Commit 4ca8cd9

Browse files
committed
Merge pull request #18 from ursenzler/master
added WhenAnyAncestorNamedLikeFactoryMethod
2 parents e6e3471 + a19bf9a commit 4ca8cd9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/Ninject.Extensions.Factory/BindToExtensions.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,42 @@ public static IBindingWithOrOnSyntax<TInterface> NamedLikeFactoryMethod<TInterfa
126126
return syntax.Named(bindingName);
127127
}
128128

129+
/// <summary>
130+
/// Defines a conditional binding that is used when any ancestor was created over the specified GetXYZ factory method.
131+
/// <seealso cref="NamedLikeFactoryMethod"/>
132+
/// </summary>
133+
/// <typeparam name="TInterface">The type of the interface.</typeparam>
134+
/// <typeparam name="TFactory">The type of the factory.</typeparam>
135+
/// <param name="syntax">The syntax.</param>
136+
/// <param name="action">Expression defining the factory method used to get the binding name from.</param>
137+
/// <returns>The <see cref="IBindingInNamedWithOrOnSyntax{TInterface}"/> to configure more things for the binding.</returns>
138+
public static IBindingInNamedWithOrOnSyntax<TInterface>
139+
WhenAnyAncestorNamedLikeFactoryMethod<TInterface, TFactory>(this IBindingWhenInNamedWithOrOnSyntax<TInterface> syntax, Expression<Action<TFactory>> action)
140+
{
141+
if (action == null)
142+
{
143+
throw new ArgumentNullException("action");
144+
}
145+
146+
var methodCallExpression = action.Body as MethodCallExpression;
147+
148+
if (methodCallExpression == null)
149+
{
150+
throw new ArgumentException("expected factory method instead of " + action, "action");
151+
}
152+
153+
var methodName = methodCallExpression.Method.Name;
154+
155+
if (!methodName.StartsWith("Get"))
156+
{
157+
throw new ArgumentException("expected factory 'Get' method instead of " + action, "action");
158+
}
159+
160+
var bindingName = methodName.Substring(3);
161+
162+
return syntax.WhenAnyAncestorNamed(bindingName);
163+
}
164+
129165
/// <summary>
130166
/// Defines that the interface shall be bound to an automatically created factory proxy.
131167
/// </summary>

0 commit comments

Comments
 (0)