几周以来,我一直在使用Simple Injector依赖注入容器,取得了巨大的成功.我喜欢简单的配置它.但现在我有一个我不知道如何配置的设计.我有一个基类,其中派生了许多类型,我想将依赖注入基类的属性,但不必为每个派生类配置.我尝试使用属性执行此操作,但Simple Injector不支持属性.这是我设计的精简版.
public interface Handler<TMessage> where TMessage : Message
{
void Handle(TMessage message);
}
public abstract class BaseHandler
{
// This property I want to inject
public HandlerContext Context { get; set; }
}
// Derived type
public class NotifyCustomerHandler : BaseHandler,
Handler<NotifyCustomerMessage>
{
public NotifyCustomerHandler(SomeDependency dependency)
{
}
public void Handle(NotifyCustomerMessage message)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我的配置现在看起来像这样:
container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here
Run Code Online (Sandbox Code Playgroud)
如何在BaseHandler中注入属性?
在此先感谢您的帮助.
我以前在我的一个属性中设置了属性注入设置
Container.RegisterInitializer<PermitAttribute>(initialize =>
{
initialize.QueryProcessor = Container.GetInstance<IQueryProcessor>();
});
Run Code Online (Sandbox Code Playgroud)
用法是
public class PermitAttribute : ActionFilterAttribute
{
public IQueryProcessor QueryProcessor { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但在更新到simpleinjector之后2.6.1属性注入破了.当我试图访问QueryProcessorPermitAttribute内的对象时.它解析了null值,因为Simple Injector配置仍然通过委托实例注入相同的属性.
由于它在v2.5中工作并且在2.6.1中不再起作用,属性注入行为是否有任何重大变化?
更新1:
配置中的Line为MVC过滤器提供程序注册v2.6.1中的属性引发了错误
container.RegisterMvcIntegratedFilterProvider();
Run Code Online (Sandbox Code Playgroud)
为此我评论了它.它阻止了房产注入工作.属性注入是我的一个属性.我猜这就是影响它的线.它在v2.6.1中抛出错误
更新2:
信息
已为另一个Container实例注册了MVC筛选器提供程序.此方法不支持为不同容器注册MVC筛选器提供程序.
堆栈跟踪 :
at SimpleInjector.SimpleInjectorMvcExtensions.RequiresFilterProviderNotRegistered(Container container)
at SimpleInjector.SimpleInjectorMvcExtensions.RegisterMvcIntegratedFilterProvider(Container container)
at RemsPortal.App_Start.SimpleInjectorInitializer.Initialize() in d:\Projects Work\RemsPortal\V2.0 Web Portal\RemsPortal\App_Start\SimpleInjectorInitializer.cs:line 39
Run Code Online (Sandbox Code Playgroud)
更新3:
整个配置
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterMvcIntegratedFilterProvider();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container Container)
{
Container.RegisterManyForOpenGeneric(typeof(IAsyncCommandHandler<,>),
AppDomain.CurrentDomain.GetAssemblies());
Container.RegisterOpenGeneric(typeof(ITransactionCommandHandler<,>),
typeof(TransactionCommandHandlerDecorator<,>)); …Run Code Online (Sandbox Code Playgroud)