Joa*_*mer 4 c# unity-container
我想知道是否有一种简单的方法可以从统一容器中删除已注册的类型,或者至少用另一个替换现有的接口/类型映射.只是将另一个类类型映射到接口并且旧的类型被覆盖了吗?
这不应该经常发生.实际上几乎没有任何时间,但有些情况我想要更换一个服务,实现与另一个接口的一些接口,而不会让其他部分受到干扰.
Eri*_*ock 11
对于Unity 2,如果您尝试将一个注册替换为另一个注册,则需要在新注册中指定From类型和To类型,如果它们包含在原始注册中.
例如,如果您有:
public interface IService
{
void DoSomething();
}
public class SomeService : IService
{
public void DoSomething();
}
public class AnotherService : IService
{
public void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
并将SomeService注册为:
container.RegisterType<IService, SomeService>();
Run Code Online (Sandbox Code Playgroud)
然后,如果您的系统的另一部分想要覆盖IService注册以解析AnotherService,您需要将其注册为:
container.RegisterType<IService, AnotherService>();
这看起来非常简单,但是当一个工厂需要创建AnotherService时我就挂了它:
container.RegisterType<IService>(new InjectionFactory(x =>
{
// this would be some complicated procedure
return new AnotherService();
}));
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您仍然可以获得SomeService.要获得像您所期望的AnotherService,您需要指定TTo类型:
container.RegisterType<IService, AnotherService>(new InjectionFactory(x =>
{
return new AnotherService();
}));
Run Code Online (Sandbox Code Playgroud)