C# 通过简单的注入器基于消费者注册装饰器
假设我有两个依赖于一个接口的服务:C# 通过简单的注入器基于消费者注册装饰器,c#,.net,dependency-injection,simple-injector,C#,.net,Dependency Injection,Simple Injector,假设我有两个依赖于一个接口的服务: class Service1 { ... Service1(IDependency dependency) { ... } ... } 及 IDependency是通过一些具体的实现注册的。如何将decorator注册到只能由Service2使用的IDependency实现?换句话说,IDependency应该只解析为Service2内部的decorator实例。可能吗 您可以使用 我真的不能这样做,因为如果我把DependencyB
class Service1
{
...
Service1(IDependency dependency) { ... }
...
}
及
IDependency是通过一些具体的实现注册的。如何将decorator注册到只能由Service2使用的IDependency实现?换句话说,IDependency应该只解析为Service2内部的decorator实例。可能吗 您可以使用
我真的不能这样做,因为如果我把DependencyBar当作decorator而不是DependencyFoo,那将使我陷入DependencyBar依赖于自身的情况。在我的例子中,使用扩展接口来区分依赖关系非常有效。这是我一直在寻找的完美答案。谢谢你们的回答。创建两个接口的一个缺点是有限/更难的可组合性。例如,如果您想装饰这些类型,该怎么办?您必须创建两个类似的装饰器。请参阅:
class Service2
{
...
Service2(IDependency dependency) { ... }
...
}
// Register decorators first
container.RegisterConditional<IDependency, DependencyDecorator1>(
c => c.Consumer.ImplementationType == typeof(Service1));
container.RegisterConditional<IDependency, DependencyDecorator2>(
c => c.Consumer.ImplementationType == typeof(Service2));
// Register the real implementation last using !c.Handled
container.RegisterConditional<IDependency, RealImplementationDependency>(
c => !c.Handled);
public interface IFileStorage
{
...
}
public interface IUploadStorage : IFileStorage { /* empty interface */ }
public interface IContentStorage : IFileStorage { /* empty interface */ }
public class FileStorage : IUploadStorage, IContentStorage
{
public FileStorage(string containerName) { ... }
...
}
public UploadService(IUploadStorage storage)
{
...
}
public ContentService(IContentStorage storage)
{
...
}
container.Register<IUploadStorage>(() = new FileStorage(Containers.Upload));
container.Register<IContentStorage>(() = new FileStorage(Containers.Content));