简体   繁体   English

如何在自定义IOC容器中使用构造函数参数解析实例?

[英]How to resolve instances with constructor parameters in custom IOC Container?

I'm trying to build my own inversion of control container. 我正在尝试构建自己的控制容器反转。 Right now I store the objects with their types in a dictionary and resolve a reference when asked. 现在,我将对象及其类型存储在字典中,并在询问时解析引用。 But I want to make it possible to resolve a reference or a new instance. 但是我想使解析引用或新实例成为可能。 I can create a new instance with the Activator class. 我可以使用Activator类创建一个新实例。 But, what if the constructor of the object to resolve takes 1, 2 or any parameters? 但是,如果要解析的对象的构造函数采用1、2或任何参数怎么办?

For example, I want to be able to say something like: 例如,我希望能够说些类似的话:

Container.register<IFoo>(new Foo(Proxy));
Container.register<IBar>(new Boo(Proxy, DataThing));

and resolve it like 并解决它像

IFoo MyFoo = Resolver.resolve<IFoo>();
IBar MyBar = Resolver.resolve<IBar>();

where MyFoo gets instanciated with the given parameter Proxy and MyBar with Proxy and DataThing . 其中MyFoo通过给定的参数Proxy和MyBar与ProxyDataThing实例化。

What does resolve have to do to make that happen? 要做到这一点必须采取什么决心

Checkout http://funq.codeplex.com . 结帐http://funq.codeplex.com This is a very tiny Container that uses lambda expressions to define the function to resolve. 这是一个非常小的Container,它使用lambda表达式来定义要解析的函数。 Handles multiple parameters. 处理多个参数。

I decided to split it in to methods. 我决定将其拆分为方法。 A Resolve, that gives back the instance stored in the container. 一个Resolve,它返回存储在容器中的实例。 And a Create that instanciate a new instance. 和创建实例的新实例。

something like: 就像是:

 public T Create<T>()
         {
             if (registeredTypes.ContainsKey(typeof(T)))
                 return (T)Activator.CreateInstance(registeredTypes[typeof(T)].
                                                                       GetType());
             else
                 throw new DependencyResolverException("Can't
                                       create type. Type " + typeof(T) + "
                                                           not found.");
         }

Activator can create an instance of a class having constructors with parameters. Activator可以创建具有构造函数和参数的类的实例。

Have a look at this overload of CreateInstance method. 看一下CreateInstance方法的这种重载。

You can provide a custom binder to search for matching constructor manually. 您可以提供一个自定义的活页夹,以手动搜索匹配的构造函数。

In your case resolve method should return reference to an instance of registered class (new Boo(Proxy, DataThing) in your example) 在您的情况下, resolve方法应该返回对已注册类的实例的引用(在您的示例中为new Boo(Proxy,DataThing))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM