簡體   English   中英

通過autofac類寄存器將DbContext對象作為參數傳遞

[英]Pass DbContext object as parameter through autofac class register

我在MVC中有一個2層體系結構應用程序(Web和Service)。 我已經在如下所示的Web項目的啟動方法中注冊了服務類,

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));
}

我已經創建了帶有接口的DbContext,如下所示

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

我有一個這樣的DbContextClass,

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

這是我的問題,我想將DbContext對象作為參數傳遞給下面的服務類,如下所示

public class SearchService : ISearchService
{
    IApplicationDbContext _dbContext;

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

我認為您在MVC控制器中使用SearchService,因此您必須在此處創建ISearchService實例。 在這種情況下,Autofac可以在控制器中進行構造函數注入。

public class ExampleController : Controller
{
    ISearchService _svc;

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

當Autofac創建ISearchService實例時,引擎將定義ISearchService需要IApplicationDbContext實例並自動創建它(相同的構造函數注入)。

因此,您只需要說Autofac,即可在其中使用IApplicationDbContext和ISearchService實例。 添加到您的Application_Start

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM