簡體   English   中英

如何在Autofac中將類的特定實現傳遞給泛型

[英]How to pass a specific implementation of a class to a generic in Autofac

我有一個通用類EfRepository<> ,它是接口IRepository<> 此類將DbContext作為其構造函數的參數。 我需要精確注入DbContext的特定子類,即ApplicationDbContext 如何在Autofac中做到這一點?

這就是我所擁有的,我想要的是:

builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .InstancePerDependency();

//The following line doesn't even compile but perhaps it can make my question clearer
builder.Register(c => new EfRepository<>(new ApplicationDbContext()))
       .As(typeof(EfRepository<>))
       .InstancePerDependency();

您無需執行任何特殊操作,只需將ApplicationDbContext注冊為DbContext

builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>));
builder.Register<ApplicationDbContext>()
       .As<DbContext>();

如果要為EfRepository<>注冊特定的DbContext ,可以使用WithParameter方法

builder.RegisterGeneric(typeof(EfRepository<>))
       .As(typeof(IRepository<>))
       .WithParameter((pi, c) => pi.ParameterType == typeof(DbContext), 
                      (pi, c) => c.ResolveNamed<DbContext>("application")); 

builder.Register<ApplicationDbContext>()
       .Named<DbContext>("application");

我使用命名注冊來受益於Autofac實例化,而不是直接實例化。

您可以在此處找到更多信息: 傳遞參數進行注冊

暫無
暫無

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

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