简体   繁体   English

创建通用存储库 <T> 用反射

[英]Create generic Repository<T> with reflection

How can I create a repository object for a custom object? 如何为自定义对象创建存储库对象? I don't know the CustomEntity type when I am creating repo object. 我在创建repo对象时不知道CustomEntity类型。

I am trying something below. 我在尝试下面的东西。

var _unitofWork = new UnitOfWork();
var objRepository = new Repository<Type.GetType("EntityName")>(_unitofWork);

Can anyone help with this? 有人能帮忙吗?

You cannot reasonably create a Repository for any arbitrary type. 您无法合理地为任意类型创建存储库。

If the objects need have nothing in common, the repository code would not know how to treat them. 如果对象不需要任何共同点,则存储库代码将不知道如何处理它们。 How would you write code to handle Customer, ComplexNumber, and System.Object? 您将如何编写代码来处理Customer,ComplexNumber和System.Object?

If the objects you are concerned with do have enough in common to be able to treat them in a common manner, express that commonality with a common base class or with an interface that they all implement. 如果您关注的对象确实具有足够的共同点,以便能够以通用方式对待它们,请使用公共基类或使用它们全部实现的接口来表达这种共性。 Then you can do 那你可以做

var rep = new Repository<IMyCommonalities>(_unitOfWork);

You can create a generic object at runtime by using MakeGenericType and Activator 您可以使用MakeGenericTypeActivator在运行时创建通用对象

var _unitofWork = new UnitOfWork();
var objRepository = Activator.CreateInstance(typeof(Repository<>).MakeGenericObject(Type.GetType("EntityName")), _unitofWork);

The only problem is that Activator.CreateInstance returns an object. 唯一的问题是Activator.CreateInstance返回一个对象。 There is no easy way to access any member without a common interface of all generic types. 没有所有泛型类型的通用接口,没有简单的方法来访问任何成员。 Maybe you have an interface like IRepository that doesn't need a generic which you can work with. 也许你有一个像IRepository这样的界面,它不需要你可以使用的泛型。 In that case cast the return value of CreateInstance to it. 在这种情况下,将CreateInstance的返回值CreateInstance为它。 If you don't have such an interface you have to use reflection or dynamic what leeds to runtime errors if you call an invalid member. 如果您没有这样的接口,则必须使用反射或动态 ,如果您调用无效成员,则会导致运行时错误。

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

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