0

I'm using dependancy injection from Unity. i..e Unity.Mvc5. I fetch all types from the various assemblies

Assembly assembly = Assembly.LoadFrom(string.Format("{0}\\{1}", AppStartPath, containerElement.InterfaceAssembly));
Assembly assembly2 = Assembly.LoadFrom(string.Format("{0}\\{1}", AppStartPath, containerElement.ConcreteClassAssembly));
Type type = assembly.GetType(containerElement.InterfaceName);
Type type2 = assembly2.GetType(containerElement.ConcreteClass);

Now the following works when I pass the types:

  container.RegisterType<IWarehouseBinController, WarehouseBinController>();

But this doesn't

container.RegisterType<type.GetTypeInfo().GetType(), type2.GetTypeInfo().GetType()>();

Anyone know why or how to resolve it? Basically I want to use this in an ASP.Net MVC site.

Eminem
  • 7,206
  • 15
  • 53
  • 95
  • A `Type` instance is not a generic arguments, which is why it doesn't work. I believe there's a [method](https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ee650414(v%3dpandp.10)) which takes `Type` objects instead of generic arguments. – ProgrammingLlama Dec 27 '18 at 07:13
  • Yeah. It is a duplicate – Eminem Dec 27 '18 at 07:23

1 Answers1

0

refereeing to this link you can see how you can do dynamic registration of all types of dependencies even the generic type , but please note that example using autofac library but i believe all of them same .

  var builder = new Autofac.ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
var assemblyTypes = assembly.GetTypes();

foreach (var type in assemblyTypes)
{
    // Ignore interfaces
    if (type.IsInterface)
        continue;

    var typeInterfaces = type.GetInterfaces();

    // Class should implement IDependecy or ISingletonDependency
    if (!typeInterfaces.Any(i => i.IsAssignableFrom(typeof(IDependency))))
        continue;

    var registration = builder.RegisterType(type).AsImplementedInterfaces();

    if (typeInterfaces.Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
        registration.SingleInstance();
    else
        registration.InstancePerRequest();
}
moath naji
  • 663
  • 1
  • 4
  • 20