简体   繁体   中英

Pass DbContext object as parameter through autofac class register

I have a 2 tier architecture application(Web and Service) in MVC. I have registered my service classes in the startup method in web project like below,

protected void Application_Start()
{
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterControllers(typeof(MvcApplication).Assembly);

    containerBuilder.RegisterModelBinders(Assembly.GetExecutingAssembly());
    containerBuilder.RegisterModelBinderProvider();

    containerBuilder.RegisterType<SearchService>().As<ISearchService>();


    var container = containerBuilder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

I have created a DbContext with interface, like below

public interface IApplicationDbContext
{
    DbSet<Customer> Customers { get; set; }
}

and I have a DbContextClass like this,

public class ApplicationDbContext : 
    IdentityDbContext<User, Role, Guid, UserLogin, UserRole, UserClaim>,
        IApplicationDbContext
{
    public ApplicationDbContext() : base("DefaultConnection")
    {
        Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDbContext>());        
    }
}

Here my question is, I want to pass DbContext object as parameter to below service class, like this

public class SearchService : ISearchService
{
    IApplicationDbContext _dbContext;

    public QueueService(IApplicationDbContext context)
    {
       _dbContext = context;
    }
}

I think you use SearchService in your MVC Controller, so u have to create ISearchService instance there. In this case Autofac can make constructor injection in you controller.

public class ExampleController : Controller
{
    ISearchService _svc;

    public B2BHealthApiController(ISearchService s)
    {
        _svc = s;
    }
}

When Autofac creates instance of ISearchService, engine defines that ISearchService require instance of IApplicationDbContext and creates it automaticly (the same constructor injection).

So you just have to say Autofac where take IApplicationDbContext and ISearchService instances. Add to your Application_Start

builder.RegisterType<ApplicationDbContext>()                
            .As<IApplicationDbContext>()
            .InstancePerDependency();

builder.RegisterType<SearchService>()               
            .As<ISearchService>()
            .InstancePerRequest();

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