【发布时间】:2017-07-11 11:03:05
【问题描述】:
关于docs of SimpleInjector 将装饰器模式与装饰工厂一起使用,我遇到了以下问题。
假设我有一个类似的ThreadScopedCommandHandlerProxy<T>,具有以下实现:
public class LifetimeScopeCommandHandlerProxy<T> : ICommandHandler<T>
{
private readonly IScopeStarter _scopeStarter;
private readonly IServiceFactory<ICommandHandler<T>> _decorateeFactory;
public LifetimeScopeCommandHandlerProxy(
IScopeStarter scopeStarter,
IServiceFactory<ICommandHandler<T>> decorateeFactory)
{
_scopeStarter = scopeStarter;
_decorateeFactory = decorateeFactory;
}
[DebuggerStepThrough]
public void Handle(T command)
{
using (_scopeStarter.BeginScope())
{
ICommandHandler<T> handler = _decorateeFactory.CreateInstance();
handler.Handle(command);
}
}
}
通常我会在代理中注入 Func<ICommandHandler<T>>,但我想从中抽象出来并创建一个 IServiceFactory,它在内部只是这样做:
public class SimpleInjectorServiceFactory<TService> : IServiceFactory<TService>
{
private readonly Func<TService> _factory;
public SimpleInjectorServiceFactory(Func<TService> factory)
{
_factory = factory;
}
public TService CreateInstance()
{
return _factory.Invoke();
}
}
您可以通过查看类名来了解其背后的原因,这是一个 Simple Injector 特定的工厂。现在我知道使用这样的工厂抽象会引入代码异味。但在这种情况下,它只能用作基础设施组件。这个想法是我希望代理可以被多个库/应用程序使用,因此使其成为应用程序架构中的通用组件。
现在问题当然是,我得到以下异常:
For the container to be able to use LifetimeScopeCommandHandlerProxy<TCommand>
as a decorator, its constructor must include a single parameter
of type ICommandHandler<TCommand> (or Func<ICommandHandler<TCommand>>)
- i.e. the type of the instance that is being decorated.
The parameter type ICommandHandler<TCommand> does not currently exist
in the constructor of class LifetimeScopeCommandHandlerProxy<TCommand>.'
现在这个异常消息非常清楚,我理解这背后的原因。但是,我还是想知道是否可以绕过异常?
【问题讨论】:
标签: c# simple-injector