Reputation: 5449
Hi I am tryng to create a generic wrapper around Unity that will enable me to change IoC frameworks whenever I want without the need of
public static void RegisterTypes(IDependencyInjectionContainerWrapper container)
{
List<Type> types = LoadTypesFromAssemblies();
foreach (var type in types)
{
var interfaceType= type.CustomAttributes
.FirstOrDefault(a => a.AttributeType.Name == typeof(DependencyService).Name)
.ConstructorArguments[0].Value;
container.RegisterType<type, interfaceType>();
}
}
What's happening here is I am getting a list types to with the attribute DependencyService is applyed.
Then I iterate over it and I am getting the first constructor argument of the attribute.
I am then attempting to Register the type in the container threw generics.This is where I am having problems.
I do not know how to pass the two types I have in the RegisterType method generics.As it stands I am getting errors because I am passing in the generic a variable not an object type
Is there anyway to solve my problem?
Upvotes: 1
Views: 153
Reputation: 148980
If the dependency container has a non-generic method, call that:
container.RegisterType(type, interfaceType);
If it doesn't have a non-generic method, and if you can modify the source, I'd strongly recommend providing one; it makes this kind of thing a lot easier. Typically, with a container like this your generic method will end up calling your non-generic one:
public void RegisterType(Type implType, Type ifaceType)
{
...
}
public void RegisterType<TImpl, TIface>() where TImpl : TIface
{
this.RegisterType(typeof(TImpl), typeof(TIface));
}
Otherwise you'll have to dynamically provide the generic parameters through reflection:
var methodInfo = container.GetType().GetMethod("RegisterType");
var actualMethod = methodInfo.MakeGenericMethod(type, interfaceType);
methodInfo.Invoke(container);
But this is neither efficient nor particular elegant.
Upvotes: 1