在Autofac中装饰现有注册

时间:2012-04-26 11:50:23

标签: c# .net autofac

我有以下界面及其实现:

public interface IService
{
}

public class Service1 : IService
{
}

public class DecoratedService
{
    public DecoratedService(IService inner)
    {
    }
}

Service1在我无法更改的代码中注册(未命名注册):

builder.RegisterType<Service1>().As<IService>();

所以我需要用自己的装饰来装饰这个注册。如何在

的范围内以最小的性能影响实现这一目标
  

public class DataModule:Autofac.Module

类?

如果我需要使用已命名的IService注册更改现有的IService注册,这是可以的(但我还没有找到方法)。我在stackoverflow中研究了所有相关的问题,但没有给我解决方案。

1 个答案:

答案 0 :(得分:1)

您应该可以替换模块中IService的现有注册,并为其提供名称。

builder.RegisterType<Service1>().Named<IService>("implementor");

然后注册指定服务的装饰器。

builder.RegisterDecorator<IService>(s => new DecoratedService(s), "implementor");

Nick有一篇博文,其中详细介绍了Autofac中的装饰器支持。

http://nblumhardt.com/2011/01/decorator-support-in-autofac-2-4/