C# – Removing already registered types from UnityContainer at runtime

c++unity-container

i wonder if there is a simple way to remove already registered types from a unity container or at least replace existing Interface/Type mappings with another one.
is it enough to just map another class type to an interface and the old one is overwritten?


this should not happen very often. actually hardly any time, but there are situations were i want to replace a service implemeting some interface with another without having the other parts disturbed.

Best Solution

With Unity 2, if you're trying to replace one registration with another you'll need to specify both the From type and To type in the new registration if they were included in the original 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 register SomeService as:


container.RegisterType<IService, SomeService>();

then if another part of your system wants to override the IService registration to resolve an AnotherService you'll need to register it as:


container.RegisterType<IService, AnotherService>();

That seems pretty straightforward, but I got hung up on it when AnotherService needed to be created by a factory:


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

In this case you'll still get SomeService. To get AnotherService like you'd expect you need to specify the TTo type:


container.RegisterType<IService, AnotherService>(new InjectionFactory(x =>
{
    return new AnotherService();
}));
Related Question