Контейнер единицы может передать ссылку себя как параметр конструктора?

Вам необходимо создать массив ключей, чтобы гарантировать порядок ключей, затем сопоставить его со значениями и соединить их запятой:

 ["name", "phone", "email"].map(k => obj[k]).join(",")
19
задан Martin G 8 October 2015 в 10:00
поделиться

3 ответа

The short answer is yes.

This should be passed automatically when you use the Resolve methods.

For example:

IUnityContainer container = new UnityContainer();
var something = container.Resolve<Something>();

Additionally, this is the same technique that Prism (on CodePlex) uses if you want to look into that.

Update Added Test:

[TestClass]
public class Spike
{
    [TestMethod]
    public void unityTest()
    {
        var container = new UnityContainer();
        var something= container.Resolve<Something>();
        Assert.AreSame(container, something.Container);
        // This passes. Success.
    }
}

public class Something
{
    public Something(IUnityContainer container)
    {
        Container = container;
    }

    public IUnityContainer Container { get; set; }
}
23
ответ дан 30 November 2019 в 04:33
поделиться

The first answer is sort of what I was thinking. Thank you.

Prior to Unity, we built our own IOC container, and we have a syntax something like...

<constructor>
    <param name="factory" value="[{factory}]"/>
</constructor>

The [{factory}] causes it to pass itself as the parameter.

As for setting it as a static: I don't like using that approach because the every object becomes dependent on the single property (obviously). Its less reusable and less testable, especially if the static is readonly (which it should be). Once the static is set, you can't (or shouldn't be able to) mess with it, which limits the test scenarios you can create.

If nothing else, then the objects should at least be able to accept a container as a parameter. If its not there, then it could fall back to a static.

We've gone down the road of using the single instance, and ended up changing it all. In my opinion, the objects should be more flexible than that. If the consumer of the objects wants to have a single instance that it passes to its objects, that's up to the consumer. But, the object themselves shouldn't require it. With the syntax shown above, its really easy to pass the container through the graph.

Thanks for the info.

Jay

Sorry... new guy. I see now this should've been a comment, not an answer.

1
ответ дан 30 November 2019 в 04:33
поделиться

As bendewey mentioned you can pass it, as it is an object, like any other object, but, why pass it?

You have only one, why not have it be a static property that any class can access?

0
ответ дан 30 November 2019 в 04:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: