Resolve may fail depending on order of RegisterInstance and RegisterType

只愿长相守 提交于 2019-12-24 07:34:57

问题


When using this object model:

interface IInterface {}

class Impl : IInterface
{
    public Impl(int blah) {}
}

And this test:

void Test1()
{
    IUnityContainer container = new UnityContainer();
    container.RegisterInstance(new Impl(3), new ContainerControlledLifetimeManager());
    container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());

    Impl impl = container.Resolve<Impl>();
}

I get an exception:

Resolution of the dependency failed, type = "BlahMain.Program+Impl", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Int32 cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving BlahMain.Program+Impl,(none)
Resolving parameter "blah" of constructor BlahMain.Program+Impl(System.Int32 blah)
Resolving System.Int32,(none)

It looks like Unity is trying to construct its own Impl instance, even though I have already registered one.

Changing the registration order as follows:

void Test2()
{
    IUnityContainer container = new UnityContainer();
    // Note: RegisterInstance is now called after RegisterType.
    container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());
    container.RegisterInstance(new Impl(3), new ContainerControlledLifetimeManager());

    Impl impl = container.Resolve<Impl>();
}

solves the issue.

Now, changing the order of registrations is an acceptable workaround, but it forces me to think when setting up the container. I was hoping that when using Unity I wouldn't have to worry about registration order.

Can anyone explain this behavior? Is this such a delicate use-case that I have to be aware of registration order?


Damian,

This is what I'm trying to do and I'm getting the same error. Is this not what you meant?

void Test3()
{
    IUnityContainer container = new UnityContainer();
    var impl = new Impl(3);
    container.RegisterInstance(impl, new ContainerControlledLifetimeManager());
    container.RegisterInstance<IInterface>(impl, new ContainerControlledLifetimeManager());
    container.RegisterType<IInterface, Impl>(new ContainerControlledLifetimeManager());

    var resolvedImpl = container.Resolve<Impl>();
}

回答1:


You should do something like:

 container.RegisterInstance<IInterface>(new Impl(3), new ContainerControlledLifetimeManager());


来源:https://stackoverflow.com/questions/5770580/resolve-may-fail-depending-on-order-of-registerinstance-and-registertype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!