简体   繁体   中英

Decorate existing registration in Autofac

I have following interface and its implementations:

public interface IService
{
}

public class Service1 : IService
{
}

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

Service1 is registered in the code that I cannot change (not named registration):

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

So I need to decorate this registration with my own. How can I achieve this with minimal performance impact in scope of

public class DataModule : Autofac.Module

class?

It's ok if I need to change existing IService registration with the named one (but I haven't found the way how to do it). I researched all related questions in stackoverflow but non of them gave me solution.

You should be able to replace the existing registration for IService in your module and provide it with a name.

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

Then register a decorator for the named service.

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

Nick has a blog post with plenty of details about the decorator support in Autofac.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM