如何在Autofac中注册一个常规接口

How to Register a conventional Interface in Autofac

我的项目中有一个autofac DI。 我想通过常规方式公开一个接口,我项目的所有其他接口都将从该接口继承。是否可以在启动级别自动注册继承接口的组件?例如:

Public interface IConvetionInterface {}
public interface IImplementationA:IConvetionInterface 
{
public void DoSomethingA();
}

public interface IImplementationB:IConvetionInterface 
{
public void DoSomethingB();
}

通过构造函数注入;

public class ConsumerA
    {
        private readonly IImplementationA _a;

        public DealerRepository(IImplementationA A)
        {
            _a= A;
        }

        public Act()
        {
            _a.DoSomethingA();


        }

    }

如何注册 IConvetionInterface 以使其所有依赖项在 Autofac 中解析。

我已经能够通过使用他们的文档页面中提供的 autofac 程序集扫描配置来提出这个解决方案 Autofac Documentation Page

我有一个开放的通用接口

public interface IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey>
    { }

实施
public class Repository<TEntity, TPrimaryKey> : RepositoryBase<TEntity, TPrimaryKey>
        where TEntity : class, IEntity<TPrimaryKey>{}

然后,我创建了一个空界面

public interface IConventionDependency
    {

    }

调用此方法以在启动级别注册我的组件:

public static void RegisterAPSComponents(ContainerBuilder builder)
        {
            builder.RegisterType<APSContext>().InstancePerRequest();
            builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)).InstancePerLifetimeScope();




  builder.RegisterAssemblyTypes(typeof(IConventionDependency).Assembly).AssignableTo<IConventionDependency>().As<IConventionDependency>().AsImplementedInterfaces().AsSelf().InstancePerLifetimeScope();



        }

通过以上注册,任何继承自IConventionDependency的接口都会自动注册到容器中。

示例: 创建接口:

public interface IDealerRepository : IConventionDependency
    {
        List<Dealers> GetDealers();
    }

然后实现接口:

public class DealerRepository : IDealerRepository
    {
        private readonly IRepository<VTBDealer, int> _repository;

        public DealerRepository(IRepository<VTBDealer, int> repository)
        {
            _repository = repository;
        }

        public List<Dealers> GetDealers()
        {
            return _repository.GetAllList().MapTo<List<Dealers>>();


        }

    }

总而言之,在没有显式注册 IDealerRepository 的情况下,它在 MVC 控制器构造函数中得到解析。