开发者

Resolving constructor paramters using the same name used for resolving the object

开发者 https://www.devze.com 2022-12-16 13:40 出处:网络
Say I have this class public class MyObject : IObject { public MyObject(IObject2 object2) { } } which I resolve like:

Say I have this class

public class MyObject : IObject
{
    public MyObject(IObject2 object2)
    {

    }
}

which I resolve like:

Container.Resolve<IObject>("SomeName");
开发者_运维问答

Is it possible to configure Unity so that whenever an IObject is resolved using any name, then the IObject2 will also be resolved with that same name (assuming it was registered with such a name)?

I'm looking for a way that doesn't use InjectionConstructor, as I son't want to update it for every new name I introduce.


This ought to work:

container.RegisterType<IObject2, MyObject2>("someName");
// ...
container.RegisterType<IObject, MyObject>("someName",
    new InjectionConstructor(
        new ResolvedParameter<IObject2>("someName")));

If you want to register more names, you could always consider packaging this little snippet into a reusable method that takes the name as an input parameter.

I don't have Unity nearby right now, so this is more or less from memory...

0

精彩评论

暂无评论...
验证码 换一张
取 消