Raising Domain Events For Multiple Subscribers

2020-06-06 06:11发布

I am stating to look into the Domain Events pattern and have read a lot of resources on the subject but I cannot find a good way of implementing for our requirements. Basically we have a Service/Domain layer which wraps the repository layer for reads/writes with a simplistic CQRS implementation. We have an ASP.NET Mvc application which consumes this service/domain layer. The whole application is tied together with Autofac and what I would like to happen is for the following:

When a news item is created by calling say "CreateNews" on the service layer register that an event will need to be raised as so:

public void CreateNews(Domain.Entities.News.NewsBO news)
{
  ValidateBusinessObject(news);

  var entityNews = AutoMapper.Mapper.Map<Repositories.Entities.News.News>(news);
  NewsCommandRepository.Create(entityNews);

  _domainEventManager.Register<NewsCreatedDomainEvent>(x => x.News = news);
}

This is all happening in a transaction and I don't want to actually raise the event until the save is completed so in our save changes method I want to do this:

public void SaveChanges()
{
  _repoCommandManager.SaveChanges();

  _domainEventManager.RaiseEvents();
}

Then in our ASP.NET Mvc application I want to have an implementation of an IHandler which looks like this:

public class NewsCreatedDomainEventCacheHandler : IHandles<Project.Services.Domain.Events.News.NewsCreatedDomainEvent>
{ 
    public void Handle(Services.Domain.Events.News.NewsCreatedDomainEvent @event)
    {
      // In here we would update the cache or something else particular to the web layer
    }
}

I cannot figure out how to go about raising this event from the save method and calling the implementation in the Web.Mvc application.

Any suggestions would be appreciated.

1条回答
够拽才男人
2楼-- · 2020-06-06 06:45

I think I have an example of how to do this for you and I happen to be using MVC and AutoFac also! In my specific example I am concentrating on Command/Query separation but in doing so I had to implement a domain event pattern.

First have a read of this blog post so you get an overview of how things hang together and what the code looks like: http://www.nootn.com.au/2013/03/command-query-separation-to-better.html

So I would recommend installing the DotNetAppStarterKit.Web.Mvc NuGet package, then take a look at the Global.asax file for how to register all the components you will need. You can peruse the SampleMvc application for things like Event Subscribers.

I hope this helps and gets you up and going quickly. You can just use the event publisher/subscriber parts of DotNetAppStarterKit without using commands and queries.

查看更多
登录 后发表回答