[英]How to register a type whose constructor takes a Func parameter in Autofac
[英]Autofac: How to pass constructor parameter for Register an Instance as a component
我的項目中有一個服務類,並且我已將上下文類(ClientIntagrationContext)注入到服務類的構造函數中,以在運行時從數據庫中提取數據,如下所示。
public AppLogsDataWriterService(AppLogsDbConnectionFactory dbFactory, IClientIntagrationContext clientIntagrationContext)
{
this.dbFactory = dbFactory;
this.clientIntagrationContext = clientIntagrationContext;
LogLevelThresholdValue = clientIntagrationContext.getApplogSettingsValue().ToString();
}
並且在解析Startup.cs文件中的服務類(AppLogsDataWriterService)時,我必須將ClientIntagrationContext類實例作為參數傳遞給“ AppLogsDataWriterService”構造函數,並且嘗試創建默認構造函數,但它會為數據庫上下文拋出NullReference異常。 那么如何在注冊我的注射類時傳遞參數?
在Startup.cs中注冊該類,
...
//IClientIntagrationContext clientIntegrationContext = new ClientIntagrationContext();
IAppLogsDataWriterService logWriterService = new AppLogsDataWriterService(logDbfactory, _________________?);
builder.RegisterInstance(logDbfactory);
builder.RegisterInstance(logWriterService);
builder.RegisterType<PlatformUserIdProvider>().As<IUserIdProvider>();
builder.RegisterHubs(typeof(UserNotificationsHub).Assembly);
var logLevelThreshold = RuntimeConfig.LogLevelThreshold;
var infoLevel = string.IsNullOrEmpty(logLevelThreshold) ? Level.Info : Level.All.Parse(logLevelThreshold);
var logWriter = RuntimeConfig.GetConfigValue<bool>("In8.Common.Logging.UseDirectWriter") ? (ILogWriter)new SqlWriter(logWriterService) : new WebWriter();
builder.RegisterAndSetupLog4NetAppLogsForWebWriter("Core", logWriter: logWriter, threshold: infoLevel);
您可以使用ContainerBuilder.Register
在服務實例化期間解決依賴關系。
例如:
builder.RegisterType<ClientIntegrationContext>().As<IClientIntegrationContext>();
builder.Register(x => new AppLogsDataWriterService(logDbfactory, x.Resolve<IClientIntegrationContext>()).AsSelf();
我們可以立即為參數類創建一個新實例,並在運行時將該實例作為參數傳遞。
Ex: var parameter= new ClientIntegrationsLogService(anyParameterInstance);
所以我如下修改了我的代碼,它的工作正常。
IExtClientIntegrationsContext iext = new ExtClientIntegrationsContext(TenantInfo.GetTenantInfoForRequest());
IClientIntegrationsLogService clientIntegrationContext = new ClientIntegrationsLogService(iext);
IAppLogsDataWriterService logWriterService = new AppLogsDataWriterService(logDbfactory, clientIntegrationContext, TenantInfo.GetTenantInfoForRequest());
否則,我們可以在“ AppLogsDataWriterService”類中為服務類創建一個新實例。 對於這種方法,無需解析或注冊我們的服務類別。
Ex:
private readonly ClientIntegrationsLogService clientIntegrationsLogService;
Constructor()
{
clientIntegrationsLogService = new ClientIntegrationsLogService(new
ExtClientIntegrationsContext(tenant));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.