IoC 容器 - 仅为特定服务注入新的 DbContext 实例
IoC container - inject new DbContext instance only for specific services
我的 C# Web 应用程序使用 Entity Framework 7 代码优先。 DbContext
的范围为 HTTP 请求的生命周期。有一个 UnitOfWork
class 包裹着这个 DbContext
。这被注入到大多数需要对数据库执行 Crud 操作的服务中。
该应用程序还有一个AuditService
,用于在抛出异常时审计错误。我不想将 HTTP 请求范围内的 DbContext
注入此服务,因为如果抛出异常,我只想将审计条目保存到数据库中,而忽略任何其他未决更改。因此在这种情况下注入 UnitOfWork
/DbContext
的新实例是有意义的。
是否可以配置 IoC 容器,以便当 UnitOfWork
被注入 AuditService
时,它应该实例化 UnitOfWork 的新实例(包装 DbContext
)?但是对于所有其他服务,应该注入范围为 HTTP 请求的 UnitOfWork
/DbContext
吗?
我正在使用 ASP.NET Core 附带的 Microsoft 内置 IoC 容器,但是使用其他 IoC 容器(例如 StructureMap)的示例也会有所帮助。
既然你已经写过使用其他 IOC 容器的例子很好,所以我将使用 Ninject 作为我回答的基础。
您想要实现的目标叫做Contextual binding。引用 Ninject wiki,您可以:
... register more than one binding for a type. There are two primary reasons one might want to register multiple type bindings
- Multiple bindings – for contextual binding taking the context into consideration
- Multiple bindings – for Multi-Injection
我认为您正在寻找第一种类型或注册,而您使用 WhenInjectedInto()
助手指定绑定约束。此类绑定的示例应如下所示:
Bind<IUnitOfWork>().To<UnitOfWork>().WhenInjectedInto(typeof(AuditService));
如果不提供,则默认object scope为Transient
,即:
A new instance of the type will be created each time one is requested.
您可以根据需要将其更改为您想要的范围,例如:
Bind<IUnitOfWork>().To<UnitOfWork>().WhenInjectedInto(typeof(AuditService)).InSingletonScope();
我的 C# Web 应用程序使用 Entity Framework 7 代码优先。 DbContext
的范围为 HTTP 请求的生命周期。有一个 UnitOfWork
class 包裹着这个 DbContext
。这被注入到大多数需要对数据库执行 Crud 操作的服务中。
该应用程序还有一个AuditService
,用于在抛出异常时审计错误。我不想将 HTTP 请求范围内的 DbContext
注入此服务,因为如果抛出异常,我只想将审计条目保存到数据库中,而忽略任何其他未决更改。因此在这种情况下注入 UnitOfWork
/DbContext
的新实例是有意义的。
是否可以配置 IoC 容器,以便当 UnitOfWork
被注入 AuditService
时,它应该实例化 UnitOfWork 的新实例(包装 DbContext
)?但是对于所有其他服务,应该注入范围为 HTTP 请求的 UnitOfWork
/DbContext
吗?
我正在使用 ASP.NET Core 附带的 Microsoft 内置 IoC 容器,但是使用其他 IoC 容器(例如 StructureMap)的示例也会有所帮助。
既然你已经写过使用其他 IOC 容器的例子很好,所以我将使用 Ninject 作为我回答的基础。
您想要实现的目标叫做Contextual binding。引用 Ninject wiki,您可以:
... register more than one binding for a type. There are two primary reasons one might want to register multiple type bindings
- Multiple bindings – for contextual binding taking the context into consideration
- Multiple bindings – for Multi-Injection
我认为您正在寻找第一种类型或注册,而您使用 WhenInjectedInto()
助手指定绑定约束。此类绑定的示例应如下所示:
Bind<IUnitOfWork>().To<UnitOfWork>().WhenInjectedInto(typeof(AuditService));
如果不提供,则默认object scope为Transient
,即:
A new instance of the type will be created each time one is requested.
您可以根据需要将其更改为您想要的范围,例如:
Bind<IUnitOfWork>().To<UnitOfWork>().WhenInjectedInto(typeof(AuditService)).InSingletonScope();