joh*_*y 5 4 c# rest dependency-injection service-locator .net-core
我正在创建一个 REST 框架,我想知道是否可以提供对服务提供者的访问,因为它将在工厂中使用。我有一个通用服务,它具有在创建和更新时触发的事件
public event Func<object, TDTO, Task> CreateEvent;
protected virtual async Task OnCreated(TDTO dto)
{
await ServiceEventHandlerRule.OnServiceEvent(CreateEvent, this, dto);
}
public async Task<TDTO> Create(TDTO dto)
{
var entity = this.DtoToEntity(dto, new TEntity());
this._context.Set<TEntity>().Add(entity);
dto = await this.SaveEntity(entity);
await OnCreated(dto);
return dto;
}
Run Code Online (Sandbox Code Playgroud)
我正在工厂的服务上注册事件,目前我公开的Func<IServiceProvider, Object, TDto> 事件注册看起来像这样,这发生在我的 startup.cs 中:
var serviceConfig = new ServiceConfiuration<User, UserDTO>();
serviceConfig.EventMapping.AddCreateEvent(async (sp, obj, dto) => {
var hubTaskQueue = sp.GetService<IHubServiceTaskQueue>();
hubTaskQueue.QueueCreate<THub, TDTO>(dto);
});
services.AddScopedRestService(serviceConfig);
Run Code Online (Sandbox Code Playgroud)
用户将需要访问其事件的一些额外依赖项,因此我已授予他们访问IServiceProvider,
在注册期间使用服务位置模式的缺点是什么?
我应该屏蔽 IServiceProvider 并进行一些通用重载来自动解决它们的依赖关系吗?
在依赖注入原则、实践和模式中,我们将服务定位器定义为:
甲服务定位器提供的应用程序组件的外组合物根与访问无界集合的挥发性依存关系。[第5.2章]
A Composition Root is a single, logical location in an application where modules are composed together. You can find a detailed description of what a Composition Root is in this excerpt from the book.
In respect to your question, the important part of the Service Locator definition is: "outside the Composition Root". In other words, accessing an unbounded set of Volatile Dependencies from within the Composition Root is fine, and is not an implementation of the Service Locator anti-pattern. Accessing them outside the Composition Root, however, is an anti-pattern.
So to answer your question, you can safely let your factory depend on the container or an abstraction that resolves an unbounded set of dependencies, as long as your factory implementation is part of the Composition Root.
You can achieve this by placing the factory's abstraction close to your application logic, while you create a factory implementation in the start-up assembly of your application.
Users will need access to a few extra dependencies for their events so I've given them access to the IServiceProvider, What is the downside of using the Service Location Pattern During Registration?
If the code that depends on the IServiceProvider is not part of the Composition Root, they use the Service Locator anti-pattern, and this should be prevented. Main problems with the Service Locator anti-pattern are:
Instead, you should let those users define their dependencies as constructor arguments.
| 归档时间: |
|
| 查看次数: |
889 次 |
| 最近记录: |