IoC:注册通过反射检索的对象/接口 [英] IoC: Registering objects/interfaces retrieved by reflection

查看:95
本文介绍了IoC:注册通过反射检索的对象/接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有一个问题,我不太清楚如何处理。当我的应用程序启动时,我需要读取配置文件,并根据从文件中读取的数据构造一些对象。使用反射构造对象 - 我寻找最合适的构造函数并调用它。我知道以这种方式构造的所有实例都实现了相同的接口 - 让我们称之为ISomeInterface。然后构造实例,而不是必须在IoC容器中注册,以便在构造对象图时使用。问题是其中一些对象也可能实现任何其他接口。它们必须在它们实现的所有接口(而不仅仅是ISomeInterface)下注册。我正在考虑使用反射来检索每个对象实现的接口列表,而不是使用IoC注册它们,但我不确定如何使用Type类的实例表示的接口注册对象。除了手动检查实例是否实现特定接口,将其类型转换为该接口以及以正常方式注册它之外,任何人都可以建议任何其他方式。值得注意的是我打算使用AutoFac。任何想法将不胜感激。



Uros

解决方案

对于蹩脚的问题,我们深表歉意。解决方案很明显,但我不知何故错过了它。要注册某个实例实现的所有接口,所有人必须做的是:



 builder.RegisterInstance(instance).AsImplementedInterfaces(); 


Hi
I have a problem which I am not quite sure how to handle. When my application starts, I need to read the configuration file and - based on the data read from the file construct some objects. The objects are constructed using reflection - I look for a most suitable constructor and invoke it. I know that all instances constructed this way implemented the same interface - let's call it ISomeInterface. Then constructed instances than have to be registered with an IoC container in order to be used when constructing the object graph. The problem is that some of those objects might also implement any other interface. and they have to be registered under all interfaces they implement(not just ISomeInterface). I was thinking about using reflection to retrieve the list of interfaces each object implements and than registering them with the IoC, but I am not sure how to register an object with the interface which is represented with an instance of Type class. Can anybody suggests any other way of doing that beside manually checking whether an instance implements a specific interface, type-casting it to that interface and than registering it in a "normal" way. It might be worth noting that I intend to use AutoFac. Any ideas will be appreciated.

Uros

解决方案

Sorry for the lame question. The solution is obvious but I somehow missed it. To register all interfaces implemented by some instance all one has to do is:

builder.RegisterInstance(instance).AsImplementedInterfaces();


这篇关于IoC:注册通过反射检索的对象/接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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