Search code examples
c#asp.net-coredependency-injectionautofac

Register context with parameter (service) in .net core using autofac


This is constructor of my context:

public MyContext(DbContextOptions<MyContext> options, ICurrentUserService currentUserService) : base(options)
{
    _currentUserService = currentUserService;
}

as you can see there is also service injected as parameter.

I registered service:

builder.RegisterType<CurrentUserService>().AsImplementedInterfaces().InstancePerLifetimeScope();

And my context:

private void RegisterContext(ContainerBuilder builder)
{
    var options = new DbContextOptionsBuilder<MyContext>();
    options.UseSqlServer(_connectionString);

    builder.Register(container => new MyContext(options.Options, ???WHAT_SHOULD_BE_HERE???)).InstancePerLifetimeScope();
}

But I'm not sure how should I register this context with that service.


Solution

  • You could resolve the desired service

    builder.Register(container => 
        new MyContext(options.Options, container.Resolve<ICurrentUserService>())
    )
    .InstancePerLifetimeScope();
    

    Or just register all the necessary types

    private void RegisterContext(ContainerBuilder builder) {
        var options = new DbContextOptionsBuilder<MyContext>();
        options.UseSqlServer(_connectionString);
        builder.RegisterInstance(options.Options).As<DbContextOption<MyContext>>();
    
        builder.RegisterType<CurrentUserService>()
            .AsImplementedInterfaces().InstancePerLifetimeScope();
    
        builder.RegisterType<MyContext>().AsSelf().InstancePerLifetimeScope();
    }