Skip to content

Commit a19bf9a

Browse files
committed
added WhenAnyAncestorNamedLikeFactoryMethod
1 parent 087dfa1 commit a19bf9a

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
@@ -124,6 +124,42 @@ public static IBindingWithOrOnSyntax<TInterface> NamedLikeFactoryMethod<TInterfa
124124
return syntax.Named(bindingName);
125125
}
126126

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

0 commit comments

Comments
 (0)