I have a small dependency injection framework, and I am trying to make it resolve Lazy<>
instances dynamically. The idea is to do something like that:
DIContainer.Register<IDbCommand,SqlCommand>();
var lazyCommand = DIContainer.Resolve<Lazy<IDbCommand>>();
I read the other day that Autofac was able of doing that.
I am stuck trying to set the constructor for that Lazy<>
instance. In the next test code, a exception is thrown because the desired type constructor is expecting a Func<arg>
, but I am passing a Func<Object>
:
static readonly Type _lazyType = typeof(Lazy<>);
static Object ResolveTest(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == _lazyType)
{
var arg = type.GetGenericArguments()[0];
return Activator.CreateInstance(_lazyType.MakeGenericType(arg), new Func<Object>(() => ResolveType(arg)));
}
else
return ResolveType(type);
}
I am out of ideas about how to create a delegate that fits for the Lazy<>
constructor parameter. Any idea?
Cheers.
This app outputs "True" and "0". I.e.
ResolveTest(typeof(Lazy<int>))
returns aLazy<int>
object, constructed like you wanted.This is a way to rewrite
ResolveTest
as a genericResolve<T>
(e.g.Resolve<int>
returnsLazy<int>
). This is a little different, since there's no equivalent toResolveTest(typeof(int))
, which returns anint
.Or with a generic
ResolveType<T>
:That's not trivial. One possible solution would be to work with reflection:
Create a generic
ResolveType
method:Create a delegate that uses this method:
Use that delegate: