Is there anyway to get autofac to resolve the service that has a concrete implementation with the constructor that matches a given parameter most specifically.
By this i mean match a constructor for a child type instead of matching the constructor for the base type.
For example i'd like to make the following test pass
[TestFixture]
public class AutofacResolvTestFixture
{
[Test]
public void test()
{
var cb = new ContainerBuilder();
cb.RegisterType<Child1>();
cb.RegisterType<Child2>();
cb.RegisterType<ServiceImpl1>().As<IService>();
cb.RegisterType<ServiceImpl2>().As<IService>();
var container = cb.Build();
var c1=container.Resolve<Child1>();
var c2=container.Resolve<Child2>();
var s1 = container.Resolve<IService>(new TypedParameter(c1.开发者_如何学编程GetType(), c1));
var s2 = container.Resolve<IService>(new TypedParameter(c2.GetType(), c2));
Assert.That(s1, Is.InstanceOf<ServiceImpl1>());
Assert.That(s2, Is.InstanceOf<ServiceImpl2>());
Assert.That(s1.ConstructorParam, Is.SameAs(c1));
Assert.That(s2.ConstructorParam, Is.SameAs(c2));
}
}
public class baseClass {}
public class Child1 : baseClass{}
public class Child2 : baseClass{}
public interface IService
{
baseClass ConstructorParam { get; }
}
public class ServiceImpl1 : IService
{
private baseClass _b;
public ServiceImpl1(baseClass b)
{
_b = b;
}
public baseClass ConstructorParam
{
get
{
return _b;
}
}
}
public class ServiceImpl2 : IService
{
private baseClass _b;
public ServiceImpl2(Child2 b)
{
_b = b;
}
public baseClass ConstructorParam
{
get
{
return _b;
}
}
}
My goal is to make IService, IEditor and be able to resolve the IEditor for a type by passing it to autofac. I want to do this so that i can "override" the editor for a type by simply inheriting IEditor and using the appropriate constructor type that that IEditor is for.
Thank you.
Take a look at my solution to this question. Perhaps you can use the same solution, with a Func<Type, IService>
factory delegate instead, and have ServiceImplX Keyed to the corresponding child type instead of using Named registrations.
精彩评论