Autofac register assembly types

前端 未结 4 990
太阳男子
太阳男子 2021-02-05 08:25

In Castle, I used to do the following to register types from a different assembly:

Classes.FromAssemblyNamed(\"MyServer.DAL\")
       .Where(type => type.Name         


        
相关标签:
4条回答
  • 2021-02-05 08:43

    Sometimes AppDomain.CurrentDomain.GetAssemblies doesn't return assemblies of dependent projects. Detailed explanation here Difference between AppDomain.GetAssemblies and BuildManager.GetReferencedAssemblies

    In those cases, we should get those project assemblies individually using any class inside the project and register its types.

    var webAssembly = Assembly.GetExecutingAssembly();
    var repoAssembly = Assembly.GetAssembly(typeof(SampleRepository)); // Assuming SampleRepository is within the Repository project
    builder.RegisterAssemblyTypes(webAssembly, repoAssembly)
                .AsImplementedInterfaces();          
    
    0 讨论(0)
  • 2021-02-05 08:49

    You can use the As's predicate overload! You can get the all of the interfaces with GetInterfaces from the given types that ends with "Repository" and then select the first interface which they implement and register it.

    var assembly = Assembly.GetExecutingAssembly();
    ContainerBuilder builder = new ContainerBuilder();
    
    builder.RegisterAssemblyTypes(assembly)
        .Where(t => t.Name.EndsWith("Repository"))
        .As(t => t.GetInterfaces()[0]);
    
    0 讨论(0)
  • 2021-02-05 08:57

    This is the correct way:

    builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
           .Where(t => t.Name.EndsWith("Repository"))
           .AsImplementedInterfaces()
           .InstancePerRequest();
    
    0 讨论(0)
  • 2021-02-05 09:06

    For UWP correct way is a bit alter:

       var assemblyType = typeof(MyCustomAssemblyType).GetTypeInfo();
    
       builder.RegisterAssemblyTypes(assemblyType.Assembly)
       .Where(t => t.Name.EndsWith("Repository"))
       .AsImplementedInterfaces()
       .InstancePerRequest();
    

    For each assembly you have take single type that belongs assembly and retrieve assembly's link from it. Then feed builder this link. Repeat.

    0 讨论(0)
提交回复
热议问题