简体   繁体   中英

Inject implementation using autofac to property or constructor

I have a scenarios where instance of a third party library needs to be injected using autofac. Library does not expose implementation class, instead gives a factory to get an instance.

Example Code

public class DBConnection
{
     public IContext context { get; set; }
     public string GetConnection()
     {
         return context.GetConfiguration("connectionString");
     }
}

IContext is part of 3rd party lib and should be initialized using Autofac with context = Configuration.Factory.GetContext(); . Ideally I can call this function in DBConnection constructor, but IContext is singleton, so better to get injected by DI container IContext implementation class is hidden so I can't register it using builder, returns implementation as interface

You can add IContext as a dependency to DbConnection

public class DBConnection
{

    public DbConnection(IContext context)
    {
        this.Context = context; 
    }

    public IContext Context { get; }
    public String GetConnection()
    {
       return this.Context.GetConfiguration("connectionString");
    }
}

And then, you can register IContext like this :

builder.Register(c => Configuration.Factory.GetContext()).As<IContext>(); 

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