Autofac Runtime Settings

I'm new to autofac and see how to better understand how to pass runtime values ​​to a constructor. I read a bunch of stackoverflow questions where this is asked, but none of them are completely complicated. Should we use delegates, factory to create a service, etc. I know that passing a container around is not the best way to accomplish this.

In my particular case, I have a service that accesses several dependencies, say, logging, a datosensor, etc. Along with several transferred services, I also have runtime parameters that I need to do, for example, userid, password. A user ID and password are required for SomeService and are viewed when the web viewer performs a specific action. Below is what I have and highlighted.

public class SomeService : ISomeService
{
    private readonly IDataProvider _dataProvider;
    private readonly ILog _log;
    private readonly string _username;  
    private readonly string _password;

    public SomeService(IDataProvider dataProvider, ILog log,
        string username, string password)
    {
      _dataProvider = dataProvider;
      _log = log;
      _username = username;
      _password = password;
    }
}

Date provider and log configured in autofac

builder.RegisterType<DataProviderService>().As<IDataProvider>()
builder.RegisterType<SomeLogService>().As<ILog>()

"SomeService" , , , , autofac. Autofac - , , , , , .

+4
2

. DI. . , , . , , IUserContext, , .

+3

AutoFac .

Func, .

. Func<string, ISomeService> myService

AutoFac Func, , factory .

:

T , Autofac Func , T .

, ISomeService . . Func<string, string, ISomeService> . factory.

:

Factory , .

- , AutoFac factory.

.

public class SomeService : ISomeService
{
    // Factory method
    public delegate SomeService Factory(string userName, string password);

    public SomeService(IDataProvider dataProvider,
        ILog log,
        string username,
        string password)
    {
        // ..

ISomeService :

public class MyClient
{
    public MyClient(SomeService.Factory serviceFactory)
    {
        // Resolve ISomeService using factory method
        // passing runtime parameters
        _myService = serviceFactory("this", "that");
    }
}

, -runtime ( IDataProvider ILog) .

+7

All Articles