对于以下代码,我将如何根据名称解决?
public interface IService
{}
public class ServiceA : IService
{}
public class ServiceB : IService
{}
public class ClassA
{
public IService service { get; set; }
public ClassA(IService service)
{
this.service = service;
}
}
public class ClassB
{
public IService service { get; set; }
public ClassB(IService service)
{
this.service = service;
}
}
注册表:
public class MyRegistry : Registry
{
public MyRegistry()
{
For<IService>().Add<ServiceA>().Ctor<IService>().Is(i => i.GetInstance<IService>("ServiceA")); // error
}
}
用法:
container = new Container(new MyRegistry());
var test = container.GetInstance<ClassA>();
问题:
ClassB IService =&gt;应该产生ServiceB
此外,有没有办法在构造函数中使用属性来指定特定类型的具体实现? (所以不必在配置中指定?)
答案 0 :(得分:0)
我们已经创建了自己的RegistrationConvention(请注意,此实现将每个插件系列注册为Singleton):
public class SingletonConvention<TPluginFamily> : IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
if (!type.IsConcrete() || !type.CanBeCreated() || !type.AllInterfaces().Contains(typeof(TPluginFamily)))
return;
registry.For(typeof(TPluginFamily)).Singleton().Use(type).Named(type.Name);
}
}
然后在我们的注册表中(未经测试):
Scan(y =>
{
y.With(new SingletonConvention<IService>());
y.Assembly(Assembly.GetExecutingAssembly().FullName);
});
For<ClassA>()
.Use<ClassA>()
.Ctor<IService >("service").Is("service",x =>
{
var service = x.GetInstance<IService>().Named("ServiceA");
return service;
})
答案 1 :(得分:0)
我让它像这样工作&gt; @ ozczcho的回答有所帮助。感谢
For<ClassA>().Use<ClassA>().Ctor<IService>("service").Is<ServiceA>();
For<ClassB>().Use<ClassB>().Ctor<IService>("service").Is<ServiceB>();