Unity Batch Register by convention

2020-03-30 07:53发布

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条回答
戒情不戒烟
2楼-- · 2020-03-30 08:22

This should work:

container.RegisterTypes(
    AllClasses.FromAssemblies(typeof(DataRepository<>).Assembly)
        .Where(t => t.Name.EndsWith("Repository")),
    WithMappings.FromAllInterfaces);
查看更多
登录 后发表回答