仿制药的服务定位器
我说过十几种类型 T
继承自 EntityObject
和 IDataObject
。 我有通用的以下接口
IDataManager<T> where T : EntityObject, IDataObject ...
我还有数据管理器的基类
BaseDataManager<T> : IDataManager<T> where T : EntityObject, IDataObject ....
我有特定的类
public class Result : EntityObject, IDataObject ....
public class ResultDataManager : BaseDataManager<Result> ...
我想实现服务定位器,它将返回 IDataManager
的实例 T
但我坚持如何在没有大量铸件的情况下以简洁的方式实现它。
有什么想法吗?
更新: 我曾经使用以下代码来发现类型,以便使用以前的服务定位器注册它们:
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.GetInterface("ISQLDataAccessManager") != null && !type.IsAbstract)
{
var manager = (ISQLDataAccessManager)Activator.CreateInstance(type);
_managers.Add(type, manager);
var typeDO = manager.GetDataObjectType();
_typeNames2Types.Add(typeDO.FullName, typeDO);
_managers2BO.Add(typeDO, manager);
}
}
看来我并不真正理解泛型的反射
I have say a dozen types T
which inherit from EntityObject
and IDataObject
.
I have generic the following interface
IDataManager<T> where T : EntityObject, IDataObject ...
I have also base class for data managers
BaseDataManager<T> : IDataManager<T> where T : EntityObject, IDataObject ....
And i have particular classes
public class Result : EntityObject, IDataObject ....
public class ResultDataManager : BaseDataManager<Result> ...
I want to implement service locator, which will return instance of IDataManager<T>
for T
But I stucked how to implement it in a neat way without a lot of castings.
Any ideas?
UPDATE:
I used to use the following code for discovering types for registring them with my previous service locator:
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.GetInterface("ISQLDataAccessManager") != null && !type.IsAbstract)
{
var manager = (ISQLDataAccessManager)Activator.CreateInstance(type);
_managers.Add(type, manager);
var typeDO = manager.GetDataObjectType();
_typeNames2Types.Add(typeDO.FullName, typeDO);
_managers2BO.Add(typeDO, manager);
}
}
It seems that I don't really understand reflection with generics
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将定位器作为单例就可以了,那么这里有一个巧妙的解决方案:
如果您无法将定位器实现为单例,我相信没有办法创建一个 Dictionary。并进行一些转换:
Here is a neat solution if having the locator as singleton is fine:
If you cannot implement the locator as singleton, I believe there is no there around creating a Dictionary<Type,object> and do some casts: