Unity Batch Register by convention

时光怂恿深爱的人放手 提交于 2019-12-19 11:49:20

问题


I'm trying to do the equivalent of the following Autofac code in Unity IoC.

builder.RegisterAssemblyTypes(typeof (DataRepository<>).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces();

This basically replaces individually registering the following:

DataSourceDataRepository : DataRepository<DataSource>, IDataSourceDataRepository

For clarity: This registers all of my Repository types as their implemented interfaces, so when i inject IDataSourceDataRepository I get a DataSourceDataRepository, etc.

In unity i've been unable to get beyond doing one at a time manually. Test code just shows a failure to register.

My attempt:

container.RegisterType<RepositoryConnection>(new HierarchicalLifetimeManager());

container.RegisterTypes(
     AllClasses.FromLoadedAssemblies().Where(t => typeof(IRepository).IsAssignableFrom(t)), getLifetimeManager: t => new TransientLifetimeManager(),
    getInjectionMembers: t=> new InjectionConstructor[] {new InjectionConstructor(typeof(RepositoryConnection)) } );

回答1:


This should work:

container.RegisterTypes(
    AllClasses.FromAssemblies(typeof(DataRepository<>).Assembly)
        .Where(t => t.Name.EndsWith("Repository")),
    WithMappings.FromAllInterfaces);


来源:https://stackoverflow.com/questions/37332025/unity-batch-register-by-convention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!