ale*_*dru 11 c# unity-container
嗨,我一直在努力告诉Unity,如果它有多个实现,我希望它将它们注入不同的类中.这就是我的意思:
比方说,我有一个接口IProductCatalogService和两个实现
ProductCatalog : IProductCatalogService和ProductCatalogService : IProductCatalogService.
我如何告诉Unity,对于类AI,我希望在我的构造函数中传递一个类型的实例,ProductCatalog而对于Class B我想要一个实例ProductCatalogService.
我在ASP.NET Web API项目中使用Unity,并在中设置了解析器GLobalConfiguration.
对于简单的1对1注册,一切正常.
这是我尝试过但它似乎不起作用:
public class DependencyServiceModel
{
public Type From { get; set; }
public Type To { get; set; }
public IEnumerable<Type> ForClasses { get; set; }
}
public void RegisterTypeForSpecificClasses(DependencyServiceModel dependencyService)
{
foreach (var forClass in dependencyService.ForClasses)
{
string uniquename = Guid.NewGuid().ToString();
Container.RegisterType(dependencyService.From,
dependencyService.To, uniquename);
Container.RegisterType(forClass, uniquename,
new InjectionConstructor(
new ResolvedParameter(dependencyService.To)));
}
}
Run Code Online (Sandbox Code Playgroud)
在DependencyServiceModel,From是接口,To是我想要实例化的对象,并且ForClasses是我想要使用ToObject的类型.
Wik*_*hla 26
在下面的示例中,您有一个实现两次的接口,并根据您的要求按需注入两个不同的客户端类.诀窍是使用命名注册.
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IFoo, Foo1>("Foo1");
container.RegisterType<IFoo, Foo2>("Foo2");
container.RegisterType<Client1>(new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1")));
container.RegisterType<Client2>(new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2")));
Client1 client1 = container.Resolve<Client1>();
Client2 client2 = container.Resolve<Client2>();
}
}
public interface IFoo
{
}
public class Foo1 :IFoo
{
}
public class Foo2 : IFoo
{
}
public class Client1
{
public Client1(IFoo foo)
{
}
}
public class Client2
{
public Client2(IFoo foo)
{
}
}
Run Code Online (Sandbox Code Playgroud)
这很可能是你做错了什么:
Container.RegisterType(forClass, uniquename,
new InjectionConstructor(
new ResolvedParameter(dependencyService.To)));
Run Code Online (Sandbox Code Playgroud)
您可以为具体类创建命名注册.相反,你应该有
Container.RegisterType(forClass, null,
new InjectionConstructor(
new ResolvedParameter(dependencyService.To, uniquename)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17713 次 |
| 最近记录: |