无法为项目结构注册Autofac

本文关键字:注册 Autofac 结构 项目 | 更新日期: 2023-09-27 17:57:52

我设计了一个web API,它使用以下结构中的实体框架与SQL服务器交互:

存储库(包含所有存储库类)

接口

public interface IRepository<TEntity>  where TEntity : IEntity
{
    Task<TEntity> GetAllAsync(int id);
}

抽象类

public abstract class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : BaseEntity
{
    protected readonly DbContext dbContext;
    protected IDbSet<TEntity> _dbEntitySet = null;
    private bool _disposed;
    public GenericRepository(DbContext dbContext)
    {
        this.dbContext = dbContext;
        _dbEntitySet = dbContext.Set<TEntity>();
    }
    public async Task<List<TEntity>> GetAllAsync()
    {
        return await _dbEntitySet.ToListAsync();
    }
}

消费者套索

public class ConsumerCLassRepository : GenericRepository<CustomerModel>
{
    public ConsumerCLassRepository (): base(new ApplicationDbContext())
    {
    }
}

--DbCOntext--交互

public interface IDbContext : IDisposable
{
    IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
}

****抽象类***

public class AbstractDbContext : DbContext, IDbContext
{
    protected ObjectContext _objectContext;
    protected DbTransaction _transaction;
    protected static readonly object Lock = new object();
    protected static bool _databaseInitialized;
    public AbstractDbContext(string connectionStringName)
        : base(string.Format("name={0}", connectionStringName))
    {
    }
    
    public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
    {
        return base.Set<TEntity>();
    }
}

--混凝土数据库全文

public class ApplicationDbContext: AbstractDbContext
{
    public ApplicationDbContext()
        : base("ApplicationContext")
    {
        Database.SetInitializer<ApplicationDbContext>(null);
    }
    #region DbSets
    public virtual DbSet<LogRelay> LogRelay{ get; set; }
    #EndRegion
}

以上所有代码都属于存储库项目

接下来是服务项目:接口

public interface IService<TOutput> where TOutput : class, new()
{
    Task<List<TOutput>> GetAllAsync(dynamic inputParameter);
}

混凝土等级

public class CustomerSiteDirectoryService : IService<InputModel>
{
    private readonly IGenericRepository<GetCustomerSiteStatus_Result> repository;
    public CustomerSiteDirectoryService(IGenericRepository<GetCustomerSiteStatus_Result> repository)
    {
        this.repository = repository;
    }
    public async Task<List<InputModel>> GetAllAsync(dynamic inputParameter)
    {
        return something;
    }
}

控制器:

public class MyApiController: ApiController
{
    private readonly IService<InputModel> _cosumerService = null;
    public MyApiController(IService<InputModel> _cosumerService )
    {
        _customerService = customerService;
    }
    public async Task<IHttpActionResult> GetMap()
    {
        var details= await _customerService.GetAllAsync(new Input());
        return Ok(details)
    }
}

Autofac配置:

private static void SetAutofacWebAPIServices(HttpConfiguration configuration)
{
    var builder = new ContainerBuilder();
    
    // Register API controllers using assembly scanning.
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    builder.RegisterGeneric(typeof(GenericRepository<>))
           .As(typeof(IGenericRepository<>))
           .InstancePerLifetimeScope();
    builder.RegisterAssemblyTypes(typeof(AbstractDbContext).Assembly)
           .Where(t => t.Name.EndsWith("DbContext"))
           .InstancePerLifetimeScope();
    builder.RegisterAssemblyTypes(typeof(AuthRepository).Assembly)
           .Where(t => t.Name.EndsWith("Repository"))
           .InstancePerLifetimeScope();
    builder.RegisterAssemblyTypes(Assembly.Load("Services"))
           .Where(t => t.Name.EndsWith("Service"))
           .AsImplementedInterfaces()
           .InstancePerLifetimeScope();
    var container = builder.Build();
    // Set the dependency resolver implementation.
    
    var resolver = new AutofacWebApiDependencyResolver(container);
    configuration.DependencyResolver = resolver;
}

现在,当我运行应用程序时,我得到一个错误

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>
        An error occurred when trying to create a controller of type 'MyApiController'. Make sure that the controller has a parameterless public constructor.
    </ExceptionMessage>
    <ExceptionType>System.InvalidOperationException</ExceptionType>
    <StackTrace>
        at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
    </StackTrace>
        <InnerException>
        <Message>An error has occurred.</Message>
        <ExceptionMessage>
            None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyAPp.API.Controllers.MyApiController' can be invoked with the available services and parameters: Cannot resolve parameter 'MyAPp.Services.IService`1[MyAPp.Models.InputModel] cusumerService' of constructor 'Void .ctor(MyAPp.Services.IService`1[MyAPp.Models.InputModel])'.
        </ExceptionMessage>
        <ExceptionType>Autofac.Core.DependencyResolutionException</ExceptionType>
        <StackTrace>
            at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        </StackTrace>
    </InnerException>
</Error>

请帮我配置Autofac,Autofac配置似乎有一些问题,我无法理解。

无法为项目结构注册Autofac

builder.RegisterAssemblyTypes(Assembly.Load("Services"))
    .Where(t => t.Name.EndsWith("Service"))

应更改为

builder.RegisterAssemblyTypes(typeof(IService<>).Assembly)
    .Where(t => t.Name.EndsWith("Service"))
    .AsClosedTypesOf(typeof (IService<>));