Removing already registered types from UnityContainer at run time?

I wonder if there is an easy way to remove already registered types from the unit container, or at least replace existing Interface / Type mappings with another. Is it simple enough to map another type of class to an interface, and the old one is overwritten?


this should not happen very often. in fact, hardly at any moment, but there are situations when I want to replace a service that implements some interface with another, without violating other parts.

+4
source share
4 answers

Listening to the webcast (see searching msdn webcasts for unity) replaces the registered types in the last win scenario. Therefore, if you use config to load your container, use the code to register the same type that one of the codes wins (the opposite is also true btw value).

+5
source

With Unity 2, if you are trying to replace one registration with another, you will need to specify the type and type From and the type of new registration if they were included in the initial registration.

For example, if you have:

public interface IService { void DoSomething(); } public class SomeService : IService { public void DoSomething(); } public class AnotherService : IService { public void DoSomething(); } 

and you will register SomeService as:

 container.RegisterType<IService, SomeService>(); 

then, if another part of your system wants to redefine IService registration for AnotherService, you need to register it as:

 container.RegisterType<IService, AnotherService>(); 

It seems pretty simple, but I hung it when AnotherService needed to be created using factory:

 container.RegisterType<IService>(new InjectionFactory(x => { // this would be some complicated procedure return new AnotherService(); })); 

In this case, you still get SomeService. To get AnotherService, as you expect, you need to specify a TTo type:

 container.RegisterType<IService, AnotherService>(new InjectionFactory(x => { return new AnotherService(); })); 
+11
source

I did not check Unity, so I can be wrong, but I think it’s impossible what you are trying to do, since with my work on our own DI function in our framework it turned out to be much more to open types first and then launch the application, therefore that you don’t need to lock the type store for each access to see which instances you want to enter into the instance, since the store is read-only, it never mutated.

0
source

You can always simply recreate the container and register new types. Most likely, it will be expensive if you need to do it again and again, I think you may have to reconsider your framework design.

0
source

All Articles