依赖注入和 .NET 属性
我有几个方法属性可以进行一些日志记录。我们的日志记录代码位于接口(ILog)后面,如果属性仅依赖于该接口而不是实现,我希望它如此。这实际上并不是关于可测试性或依赖倒置,而是关于保持组件的耦合干净。
一个例子是我们有一个特定于 Web (Mvc) 的属性,如下所示:
HandleExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext context)
{
LogFactory.CreateInstance().Info("message here", "log entry type");
}
}
LogFactory 依赖于 Log.cs 的具体实现。不幸的是,这会导致我的 Web DLL 与包含具体实现的 DLL 耦合,从而使整个系统变得更加僵化和脆弱。
在任何其他位置,这种依赖关系变得明显,我们只需使用 IOC 容器来注入它。这正是我现在想要使用该属性执行的操作,但我不太确定该怎么做!
所以,我的问题是:如何将具体的依赖项注入到接口后面的 .NET Framework 属性中(最好通过像 StructureMap 这样的 IOC 容器 - 但任何有效的都可以)?
I have a couple of method attributes which do some logging. Our logging code sits behind an interface (ILog) and I'd like it if the attributes were only dependent upon that interface as opposed to an implementation. This isn't really about testability or dependency inversion so much as it is about keeping the coupling of components clean.
An example would be where we have a web (Mvc) specific attribute as follows:
HandleExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext context)
{
LogFactory.CreateInstance().Info("message here", "log entry type");
}
}
LogFactory is dependant upon the concrete implementation Log.cs. This has the unfortunate effect of coupling my Web DLL to the DLL containing the concrete implementation - making the overall system more rigid and fragile.
Any other location where such a dependency becomes apparent we just use our IOC container to inject it. This is exactly what I'd like to do now with the attribute but I'm not really sure how to!
So, my question is: How can a concrete dependency be injected into a .NET Framework attribute behind an interface (preferably via an IOC container like StructureMap - but anything that works will be fine)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅这篇文章 - 如何使用 Ninject 将依赖项注入 ASP.NET MVC ActionFilters
http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject -依赖项-into-asp.net-mvc.aspx
See this article - How to use Ninject to inject dependencies into ASP.NET MVC ActionFilters
http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx
您不能将记录器设置为接口并将其传递给属性中的属性或通过构造函数传递吗:
如果是我,我会选择将记录器放入基类中并在其上设置属性。
Could you not make the logger an interface and pass it to either a property in the Attribute or through the constructor:
If it were me though I would go for putting the logger in a base class and set up a property on it.