我是IoC和依赖注入的初学者。我正在读,但就是搞不懂。当我弄清楚东西是如何工作的时候,我正试图在我的项目中实现其中的一些模式(也许通过试错来学习)。
我正在通过使用FluentSecurity包(来自NuGet,顺便说一句)实现安全控制。我需要实现一个策略违反处理程序,如本wiki所述。问题是这个例子是为StructureMap iocc -container编写的,我正在使用(或试图使用)Ninject 2.2(对于初学者来说似乎更简单)。
在他们的代码中,他们建议(a):configuration.ResolveServicesUsing(type => ObjectFactory.GetAllInstances(type).Cast<object>());
然后(b):
public class WebRegistry : Registry
{
public WebRegistry()
{
Scan(scan =>
{
scan.TheCallingAssembly();
scan.AddAllTypesOf<IPolicyViolationHandler>();
});
}
}
我的担心:
- 我知道代码(a)将包含在
Global.asax
上。但是,Ninject的ObjectFactory.GetAllInstances()
替代品是什么? - 我不知道应该在哪里插入这段代码,也不知道
WebRegistry
,Scan
和内部函数TheCallingAssembly
和AddAllTypesOf
的等效物是什么。
Marius Schulz写了一篇很棒的文章,应该可以帮助任何想要将Ninject与FluentSecurity一起使用的人。
设置FluentSecurity使用Ninject进行依赖项解析
我认为这大致相当于
//add an instance of IKernel to your MvcApplication
[Inject]
public IKernel Kernel { get; set; }
...
configuration.ResolveServicesUsing(type => Kernel.GetAll(type));
要获得扫描程序集查找依赖项的能力,您需要为ninject提供一个名为ninject . extensions的扩展。
public class WebModule : NinjectModule
{
public WebModule()
{
Kernel.Scan(a => {
a.FromAssemblyContaining<YourType>();
a.BindWithDefaultConventions();
a.InTransientScope();
});
}
}
汇编扫描业务显然不是你所做的严格必要的,这将工作得很好。就我个人而言,我不是汇编扫描的粉丝,因为它似乎有点太"神奇"了,当它不起作用时,调试就不有趣了。
Kernel.Bind<YourType>().ToSelf();
我有同样的问题,你有Ninject。经过几个小时的谷歌搜索,我从github下载了源代码。我理解了代码,并调试了一些方法来弄清楚如何解析服务。我所要做的就是提供一个服务定位器来查找PolicyViolationException处理程序。
Ninject等价好像是这样的。
configuration.ResolveServicesUsing(type => System.Web.Mvc.DependencyResolver.Current.GetServices(type));
我使用Ninject MVC3,我使用下面的代码从我当前的MVC web项目和其他程序集加载模块。
private static void RegisterServices(IKernel kernel)
{
kernel.Load("*.dll");
//kernel.Load(Assembly.GetExecutingAssembly());
}
我在模块中配置了PolicyViolationException处理程序:
public class MainWebNinjectModule : NinjectModule
{
public override void Load()
{
// other bindings here
Bind<IPolicyViolationHandler>().To<DenyAnonymousAccessPolicyViolationHandler>();
}
}
其他必需的依赖,如ISecurityHandler, ISecurityContext等,由FluentSecurity中使用的内部IoC解析。