[英]How can I add an event listener to an object that is instantiated with dependency injection?
Seeing as I don't have a variable to work with when using dependency injection, how would I add an event listener to a service?看到我在使用依赖注入时没有可使用的变量,我将如何将事件侦听器添加到服务中?
Here is the ProjectService这是项目服务
public class ProjectService
{
protected AppDbContext _db;
public ProjectService(AppDbContext db)
{
_db = db;
}
public IQueryable<Project> GetProjects()
{
return _db.Projects;
}
public Project CreateProject (Project Project)
{
Project project = _db.Projects.Add(Project).Entity;
OnProjectCreated(project);
_db.SaveChanges();
return project;
}
public Project UpdateProject (Project Project)
{
Project project = _db.Projects.Update(Project).Entity;
_db.SaveChanges();
return project;
}
public Project DeleteProject (Project Project)
{
_db.Projects.Remove(Project);
_db.SaveChanges();
return Project;
}
public event EventHandler<ProjectEventArgs> ProjectCreated;
protected virtual void OnProjectCreated(Project project)
{
ProjectCreated?.Invoke(this, new ProjectEventArgs(project));
}
}
and this is how I inject it这就是我注入它的方式
services.AddTransient<ProjectService>();
It is possible to use a factory delegate.可以使用工厂委托。 Within the delegate the target type can be initialized with its dependencies and then subscribing to the event.
在委托中,可以使用其依赖项初始化目标类型,然后订阅事件。
services.AddTransient<ProjectService>(sp => {
AppDbContext dependency = sp.GetService<AppDbContext>();
ProjectService target = new ProjectService(dependency);
target.ProjectCreated += some_event_handler_here;
return target;
});
But there are many problems that can arise out of this approach.但是这种方法可能会产生许多问题。
The handler would end up living in startup.处理程序最终将生活在启动中。
The DbContext could become a captive dependency depending on its lifetime scope. DbContext 可能成为强制依赖项,具体取决于其生命周期 scope。
Since the nature of the target class is unclear based on its current design, it is uncertain how the target is to be used.由于目标 class 的性质基于其当前设计尚不清楚,因此不确定如何使用目标。
I would however suggest changing the design to use mediator pattern, and pass any notification on to a mediator that can route it to any subscribed handlers.但是,我建议将设计更改为使用调解器模式,并将任何通知传递给调解器,调解器可以将其路由到任何订阅的处理程序。 This follows more closely to Single Responsibility Principle and Separation of Concerns.
这更接近于单一职责原则和关注点分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.