user1618825
user1618825

Reputation:

Autofac - Using Multiple Implementation

With Autofac, I am registering 2 implementations with a type. And need to swap the implementations on demand. But it is always taking one implementation.

public class DataAccesss
{
    public IDatabaseHelper { get; set; }
}

Autofac

builder.RegisterType<DatabaseHelper>()
       .Named<IDatabaseHelper>("Sql")
       .WithParameter(new TypedParameter(IDatabaseHelper), new DatabaseHelper(new SqlFactory))
       .PropertiesAutowired();

builder.RegisterType<DatabaseHelper>()
       .Named<IDatabaseHelper>("Oledb")
       .WithParameter(new TypedParameter(IDatabaseHelper), new DatabaseHelper(new OleDbFactory))
       .PropertiesAutowired();

And in controller, need to have something like this

1st - need to access `IDatabaseHelper` with `OleDb`
2nd - need to access  `IDatabaseHelper` with `Sql`

But my issue is IDatabaseHelper is either null or it is always taking OleDb and not Sql.

Upvotes: 3

Views: 4630

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16192

When you resolve a single component Autofac will return the latest registered component that match the operation.

If you need to access both service in your implementation you can have a dependency on IEnumerable<IDatabaseHelper> which will resolve all IDatabaseHelper registered service.

Another solution would be to rely on IIndex<TKey, TValue> and named registration

public class XController 
{
    public XController(IIndex<String, IDatabaseHelper> databaseHelpers) 
    {
        this._databaseHelpers = databaseHelpers; 
    }

    private readonly IIndex<String, IDatabaseHelper> _databaseHelpers;

    public void Do()
    {
        IDatabaseHelper oledb = this._databaseHelpers["Oledb"];
    }
}

and your registration will be like :

builder.Register(c => new DatabaseHelper(new SqlFactory()))
       .Named<IDatabaseHelper>("Sql")
       .PropertiesAutowired();

builder.Register(c => new DatabaseHelper(new OleDbFactory()))
       .Named<IDatabaseHelper>("Oledb")
       .PropertiesAutowired();

See Named and Keyed service from Autofac documentation for more information

Upvotes: 5

Related Questions