依赖注入和.NET属性属性、NET

由网友(习惯了不习)分享简介:我有几个方法,属性里面做一些记录。我们的记录code坐在一个接口(ILog的)后面,我想,如果,而不是一个实现的属性只依赖于该接口。这是不是真正的可测试性或依赖性倒置这么多,因为它是关于保持元件清洁的耦合。 I have a couple of method attributes which do some logg...

我有几个方法,属性里面做一些记录。我们的记录code坐在一个接口(ILog的)后面,我想,如果,而不是一个实现的属性只依赖于该接口。这是不是真正的可测试性或依赖性倒置这么多,因为它是关于保持元件清洁的耦合。

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.

的一个例子是,我们有一个腹板(MVC)特定属性如下:

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依赖于具体实现Log.cs.这有耦合我的Web DLL包含具体落实该DLL的不幸影响 - 使整个系统更加僵化和脆弱。

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.

任何其他地方,这样的依赖变得明显,我们只是用我们的IOC容器注入它。这正是我想现在的属性做,但我真的不知道怎么样!

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!

所以,我的问题是:如何能够具体的依赖来(pferably通过IOC容器像StructureMap $ P $ - 但任何工作都会好起来的)注射到后面的接口的.NET框架的属性。

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)?

推荐答案

你能不能使记录器的接口,并把它传递到一个在属性或通过constructor属性:

Could you not make the logger an interface and pass it to either a property in the Attribute or through the constructor:

LoggerAttribute
{
    [Dependency]
    public ILogger Logger {get; set;}

    ...
}

如果是我,但我会去把记录在一个基类,设置了一个属性就可以了。

If it were me though I would go for putting the logger in a base class and set up a property on it.

阅读全文

相关推荐

最新文章