Resolve dependency with autofac based on constructor parameter attribute

后端 未结 2 1653
甜味超标
甜味超标 2020-12-18 09:11

I\'m using Autofac. I want to inject a different implementation of a dependency based on an attribute I apply to the constructor parameter. For example:

clas         


        
2条回答
  •  眼角桃花
    2020-12-18 09:56

    It sounds like you want to provide different implementations of IObjectContainer to CustomerRepository and FooRepository. If that is the case, attributes might be a thin metal ruler. Instead, I'll show you how I would implement multiple implementations with Autofac.

    (Calls such as .ContainerScoped() have been left out for brevity.)

    First, register a version of IObjectContainer for each connection string by naming the registrations:

    builder
        .Register(c => new ObjectContainer(ConnectionStrings.CustomerDB))
        .As()
        .Named("CustomerObjectContainer");
    
    builder
        .Register(c => new ObjectContainer(ConnectionStrings.FooDB))
        .As()
        .Named("FooObjectContainer");
    

    Then, resolve the specific instances in the repository registrations:

    builder.Register(c => new CustomerRepository(
        c.Resolve("CustomerObjectContainer"));
    
    builder.Register(c => new FooRepository(
        c.Resolve("FooObjectContainer"));
    

    This leaves the repositories free of configuration information:

    class CustomerRepository
    {
        public CustomerRepository(IObjectContainer db) { ... }
    }
    
    class FooRepository
    {
        public FooRepository(IObjectContainer db) { ... }
    }
    

提交回复
热议问题