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.
You cannot have partially opened classes. You can see this question .
But you can pass a parameter to a register .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.