I have the following two interfaces.
public interface IRegisterToContainer
{
}
public interface IRegisterPerRequest<T> : IRegisterToContainer
{
}
public interface IRegisterPerRequest : IRegisterToContainer
{
}
The two interfaces will be used by the application bootstrapper to register classes into the IoC controller using reflection.
I basically want to take any class that implements these interfaces and register it to the container.
This is how I am trying to use reflection to register these types
var types = AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly => assembly.IsDynamic == false)
.SelectMany(assembly => assembly.GetTypes()) .Where(x => x.IsClass && !x.IsInterface) .ToList();
foreach (Type type in types)
{
// Here I am trying to find any type that is assignable from the IRegisterPerRequest<> interface
if (type.IsGenericType && typeof(IRegisterPerRequest<>).IsAssignableFrom(type))
{
container.RegisterType(type.GetGenericArguments()[0], type, type.FullName, new PerRequestLifetimeManager());
}
// Here if the type implements the IRegisterPerRequest, I want to register it
else if (typeof(IRegisterPerRequest).IsAssignableFrom(type))
{
container.RegisterType(typeof(IRegisterPerRequest), type, type.FullName, new PerRequestLifetimeManager());
}
}
But for some reason, the first conditions is not being detected. Here is an use-case example
public interface ICarService
{
public Car GetCarByShape(sting shape);
}
public class CarService ICarService, IRegisterPerRequest<ICarService>
{
protected ICarRepository CarContext;
public CarService(ICarRepository car)
{
CarContext = car;
}
public Car GetCarByShape(sting shape)
{
return CarContext.Find(x => x.Shape == shape)
.FirstOrDefault();
}
}
I am basically trying to tell unity, register the type ICarService
to CarService
at run time.
How can I correctly use reflection to check of the given type implements the IRegisterPerRequest<T>
interface?
Aucun commentaire:
Enregistrer un commentaire