Registration duplication prevention - Castle Windsor

sorry if this was asked before I tried to do some google-ing and didn't find any matches, so here goes ....

I have a Castle Windsor container that I add to my components using the following method (where the container is an instance of IWindsorContainer ) ...

 container.Register(AllTypes.FromAssemblyNamed("App.Infrastructure") .Where(x => !x.IsAbstract && !x.IsInterface) .WithService.DefaultInterface() 

This works fine, however I want to register another DLL in the same way to resolve dependencies on this ...

 container.Register(AllTypes.FromAssemblyNamed("App.Client.Infrastructure") .Where(x => !x.IsAbstract && !x.IsInterface) .WithService.DefaultInterface() 

Now, anyway, I can get Windsor to notify me if the same interface resolution is added, i.e. there is only one performer per interface (take the first if more than one exists).

Hope I explained quite well. I am using Castle Windsor version: 2.5.1.0 and updating / changing the version is not really options.


Update:

I solved this by deleting duplicate registrations after registering them. After registration is complete, I get a loop below ...

 var registeredServices = new Dictionary<Type, string>(); foreach (var node in container.Kernel.GraphNodes) { var cmp = ((Castle.Core.ComponentModel)node); Type t = cmp.Service; if (registeredServices.ContainsKey(t)) container.Kernel.RemoveComponent(cmp.Name); else registeredServices.Add(t, cmp.Implementation.FullName); } 
+4
source share
2 answers

I don’t know if you can configure registrars to throw exceptions, but this simple piece of code can help you

 var registeredServices = new List<Type>(); foreach (var node in container.Kernel.GraphNodes) { foreach (var t in ((Castle.Core.ComponentModel)node).Services) { if (registeredServices.Contains(t)) throw new Exception(string.Format("service {0} already registered", t)); registeredServices.Add(t); } } 
+6
source

In 2.5, you can, after registering everything, call

 var allHandlers = container.Kernel.GetAssingableHandlers(typeof(object)); 

then you can look at each .Service handler and find out if there are any duplicates, and either throw a useful exception or something on these lines.

I would suggest that this is what you want to do in the test, and not at run time.

+4
source

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


All Articles