在我的项目中有一个服务类,我已经将我的上下文类(ClientIntagrationContext)注入到服务类的构造函数中,以便在运行时从DB中提取数据,如下所示。
public AppLogsDataWriterService(AppLogsDbConnectionFactory dbFactory, IClientIntagrationContext clientIntagrationContext)
{
this.dbFactory = dbFactory;
this.clientIntagrationContext = clientIntagrationContext;
LogLevelThresholdValue = clientIntagrationContext.getApplogSettingsValue().ToString();
} 在解析Startup.cs文件中的服务类(AppLogsDataWriterService)时,我必须将ClientIntagrationContext类实例作为参数传递给"AppLogsDataWriterService“构造函数,并且我尝试创建一个默认构造函数,但它抛出了DB Context的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); 发布于 2018-09-25 21:40:14
我们可以立即为参数类创建一个新实例,并在运行时将该实例作为参数传递。
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));
}发布于 2018-09-05 21:16:06
您可以使用ContainerBuilder.Register来解决服务实例化过程中的依赖关系。
例如:
builder.RegisterType<ClientIntegrationContext>().As<IClientIntegrationContext>();
builder.Register(x => new AppLogsDataWriterService(logDbfactory, x.Resolve<IClientIntegrationContext>()).AsSelf();https://stackoverflow.com/questions/52182210
复制相似问题