根据 RegisterInstance 和 RegisterType 的顺序,解析可能会失败 [英] Resolve may fail depending on order of RegisterInstance and RegisterType

查看:25
本文介绍了根据 RegisterInstance 和 RegisterType 的顺序,解析可能会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此对象模型时:

interface IInterface {}

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

这个测试:

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

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

我得到一个例外:

依赖解析失败,type = "BlahMain.Program+Impl", name = "(none)".
异常发生时:解决时.
异常为: InvalidOperationException - 无法构造 Int32 类型.您必须配置容器以提供此值.
<代码>-----------------------------------------------
发生异常时,容器为:
解析 BlahMain.Program+Impl,(none)
解析构造函数BlahMain.Program+Impl(System.Int32 blah)的参数"blah"
解析 System.Int32,(none)

看起来 Unity 正在尝试构建自己的 Impl 实例,尽管我已经注册了一个.

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

更改注册顺序如下:

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>();
}

解决问题.

现在,更改注册顺序是一种可以接受的解决方法,但它迫使我在设置容器时进行思考.我希望在使用 Unity 时我不必担心注册顺序.

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?

达米安

这就是我想要做的,但我遇到了同样的错误.这不是你的意思吗?

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>();
}

推荐答案

你应该这样做:

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

这篇关于根据 RegisterInstance 和 RegisterType 的顺序,解析可能会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆