Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Resolve factory delegates #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/TinyIoC.Tests/TinyIoC.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
<Compile Include="TestData\NestedInterfaceDependencies.cs" />
<Compile Include="TestData\TinyMessengerTestData.cs" />
<Compile Include="TestData\UtilityMethods.cs" />
<Compile Include="TinyIoCResolveFactoryDelegateTests.cs" />
<Compile Include="TinyIoCFunctionalTests.cs" />
<Compile Include="TinyIoCTests.cs" />
<Compile Include="TinyMessageSubscriptionTokenTests.cs" />
Expand Down
50 changes: 50 additions & 0 deletions src/TinyIoC.Tests/TinyIoCResolveFactoryDelegateTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TinyIoC.Tests.TestData;

namespace TinyIoC.Tests
{
[TestClass]
public class TinyIoCResolveFactoryDelegateTests
{
class Example
{
public delegate Example Factory(int value);

public Example(int value, Dependency dependency)
{
Value = value;
Dependency = dependency;
}

public int Value { get; private set; }
public Dependency Dependency { get; private set; }
}

class Dependency
{
}

[TestMethod]
public void Resolve_FactoryDelegate_ReturnsDelegateThatCanConstructInstance()
{
var container = UtilityMethods.GetContainer();

var factory = container.Resolve<Example.Factory>();
var createdObject = factory(1);

Assert.AreEqual(1, createdObject.Value);
Assert.IsNotNull(createdObject.Dependency);
}

[TestMethod]
public void Resolve_FactoryDelegate_CachesDelegate()
{
var container = UtilityMethods.GetContainer();

var factory1 = container.Resolve<Example.Factory>();
var factory2 = container.Resolve<Example.Factory>();

Assert.AreSame(factory1, factory2);
}
}
}
132 changes: 130 additions & 2 deletions src/TinyIoC/TinyIoC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2986,8 +2986,12 @@ private bool IsIEnumerableRequest(Type type)

private bool IsAutomaticLazyFactoryRequest(Type type)
{
var isDelegate = typeof (Delegate).IsAssignableFrom(type);

if (!type.IsGenericType)
return false;
{
return isDelegate;
}

Type genericType = type.GetGenericTypeDefinition();

Expand All @@ -3003,6 +3007,9 @@ private bool IsAutomaticLazyFactoryRequest(Type type)
if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<String, object>)))
return true;

if (isDelegate)
return true;

return false;
}

Expand Down Expand Up @@ -3130,8 +3137,14 @@ private object ResolveInternal(TypeRegistration registration, NamedParameterOver
#if EXPRESSIONS
private object GetLazyAutomaticFactoryRequest(Type type)
{
var isDelegate = typeof(Delegate).IsAssignableFrom(type);

if (!type.IsGenericType)
return null;
{
return isDelegate
? factoryDelegateBuilder.BuildFactory(type, this)
: null;
}

Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
Expand Down Expand Up @@ -3185,6 +3198,12 @@ private object GetLazyAutomaticFactoryRequest(Type type)
return resolveLambda;
}

// Any other type of delegate.
if (isDelegate)
{
return factoryDelegateBuilder.BuildFactory(type, this);
}

throw new TinyIoCResolutionException(type);
}
#endif
Expand Down Expand Up @@ -3399,5 +3418,114 @@ public void Dispose()
}

#endregion

#region Automatic factory delegate builder

// Example:
// A class where only some constructor arguments should be resolved by the container.
// Add a public factory delegate.
//
// public class Logger
// {
// public delegate Logger Factory(int indent);
//
// public Logger(int indent, IOutput output)
// {
// ...
// }
// }
//
// We can now resolve the factory delegate.
// var loggerFactory = container.Resolve<Logger.Factory>();
// var logger = loggerFactory(4);
// The created Logger instance will have indent=4 and output={whatever the container provided}.

#if EXPRESSIONS
readonly FactoryDelegateBuilder factoryDelegateBuilder = new FactoryDelegateBuilder();

class FactoryDelegateBuilder
{
static readonly MethodInfo genericResolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new[] { typeof(NamedParameterOverloads) });
static readonly MethodInfo addMethod = typeof(NamedParameterOverloads).GetMethod("Add");
static readonly ConstructorInfo namedParameterOverloadsConstructor = typeof(NamedParameterOverloads).GetConstructor(new Type[0]);

readonly Dictionary<Type, Delegate> delegateCache = new Dictionary<Type, Delegate>();

public object BuildFactory(Type delegateType, TinyIoCContainer container)
{
lock (delegateCache)
{
Delegate factory;
if (!delegateCache.TryGetValue(delegateType, out factory))
{
factory = CreateFactoryDelegate(delegateType, container);
delegateCache[delegateType] = factory;
}
return factory;
}
}

Delegate CreateFactoryDelegate(Type delegateType, object container)
{
// Create a delegate like this:
// (p1, p2, ...) => container.Resolve<T>(new NamedParameterOverloads() {
// { "p1", p1 },
// { "p2", p2 },
// ...
// })

// So any T constructor parameters not matching factory delegate parameters will be
// resolved from the container.

var delegateInvokeMethod = delegateType.GetMethod("Invoke");
var parameters = CreateParameters(delegateInvokeMethod);
var resolveCall = CreateResolveCallExpression(delegateInvokeMethod.ReturnType, parameters, container);

var lambdaExpression = Expression.Lambda(delegateType, resolveCall, parameters);

return lambdaExpression.Compile();
}

MethodCallExpression CreateResolveCallExpression(Type returnType, IEnumerable<ParameterExpression> parameters, object container)
{
var resolveMethod = genericResolveMethod.MakeGenericMethod(returnType);
var namedParameterOverloads = CreateNamedParameterOverloadsInitializerExpression(parameters);
// container.Resolve<returnType>(namedParameterOverloads);
return Expression.Call(
Expression.Constant(container),
resolveMethod,
namedParameterOverloads
);
}

ListInitExpression CreateNamedParameterOverloadsInitializerExpression(IEnumerable<ParameterExpression> parameters)
{
// new NamedParameterOverloads { { "p1", p1 }, { "p2", p2 }, ... }
return Expression.ListInit(
Expression.New(namedParameterOverloadsConstructor),
parameters.Select(CreateElementInit)
);
}

ElementInit CreateElementInit(ParameterExpression parameter)
{
// .Add("parameterName", parameterValue)
return Expression.ElementInit(
addMethod,
Expression.Constant(parameter.Name),
Expression.Convert(parameter, typeof(object))
);
}

static ParameterExpression[] CreateParameters(MethodInfo delegateInvokeMethod)
{
return delegateInvokeMethod
.GetParameters()
.Select(p => Expression.Parameter(p.ParameterType, p.Name))
.ToArray();
}
}
#endif
#endregion
}
}