问题描述:

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>(); 
相关阅读:
Top