Using Ninject with Udi Dahan Domains

I use Ninject in an MVC project and try to implement domain events after the Udi Dahan template http://www.udidahan.com/2009/06/14/domain-events-salvation/

In the passage below, β€œContainer” is used to allow all event handlers for the specific type of events that were raised.

My question (and apologies if I miss something basic) how to do it with Ninject? In other words:

  • How is Container installed in this static class?

  • As soon as I have a container (kernel?), What Ninject syntax should all event handlers allow (which, I assume, will have to be registered in the service module in advance)?

I keep reading in the posts that you need to use only the constructor injection, and everything is recursively solved from this, and that access to the Ninject core is no-no. Therefore, any advice on how to do this would be greatly appreciated.

Extract from article

public static class DomainEvents { [ThreadStatic] //so that each thread has its own callbacks private static List<Delegate> actions; public static IContainer Container { get; set; } //as before //Registers a callback for the given domain event public static void Register<T>(Action<T> callback) where T : IDomainEvent { if (actions == null) actions = new List<Delegate>(); actions.Add(callback); } //Clears callbacks passed to Register on the current thread public static void ClearCallbacks () { actions = null; } //Raises the given domain event public static void Raise<T>(T args) where T : IDomainEvent { if (Container != null) foreach(var handler in Container.ResolveAll<Handles<T>>()) handler.Handle(args); if (actions != null) foreach (var action in actions) if (action is Action<T>) ((Action<T>)action)(args); } } 
+4
source share
1 answer

How is Container installed in this static class?

You will need to install it during application launch:

 DomainEvents.Container = kernel; 

What will be the Ninject syntax for resolving all event handlers:

You can do this, for example:

 Container.Get<IEnumerable<Handles<T>>>()) 

The Udi class static DomainEvents is an implementation of the environment context template. Ambient context is a template that is used only in a limit on the number of scenarios. In this case, I would prefer to use dependency injection to insert the IDomainEvents abstraction into the code that she needs, rather than the code dependent on a static instance.

However, the problem is that the objects in your domain will require a dependency on IDomainEvents , and constructor injection is (possibly) impossible. The trick is to use the injection method in this case.

In other words, use the constructor injection to inject IDomainEvents into command or service handlers (or what you ever call your business logic, which uses methods on domain objects), and pass this dependency to the domain object when you call the method that needed (injection method).

+6
source

Source: https://habr.com/ru/post/1441327/


All Articles