2021年1月24日星期日

How to resolve generic type with dynamic parameter?

I have a generic class like

class EntityDao<T> where T: class  {      void Update(T entity)      {         //Update entity to somewhere.      }  }  

while T might be any classes, like User, Company and etc.

I use Autofac to register EntityDao as Generic Type.

var builder = new ContainerBuilder();  builder.RegisterGeneric(typeof(EntityDao<>));  var container = builder.Build();  

In other places, I want to resove it dynamically.

string typeName = "User"; // might be "Company" or any other type name.    switch (typeName)  {      case "User":          container.Resolve<EntityDao<User>>().Update(entity);          break;      case "Company":          container.Resolve<EntityDao<Company>>().Update(entity);          break;      default:          break;  }  

Here, typeName might have more than 50 values, and I thing there should be a generic way to avoid writing 50 cases.

Thanks in advance for any ideas.

https://stackoverflow.com/questions/65878471/how-to-resolve-generic-type-with-dynamic-parameter January 25, 2021 at 11:07AM

没有评论:

发表评论