簡體   English   中英

無法使用autofac解析通用存儲庫的依賴性

[英]Unable to resolve dependency for generic repository using autofac

我正在使用.net核心API並使用autofac解析我的依賴項。 但是不知怎的,我無法解決我的Generic Repository的依賴關系。

有人可以指導我做錯了什么。

startup.cs

var builder = new ContainerBuilder();

builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
    .InstancePerLifetimeScope();

builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>()
.InstancePerLifetimeScope();

//This is the place which is not working for me
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

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

builder.RegisterAssemblyTypes(typeof(UserService).Assembly)
    .Where(t => t.Name.EndsWith("Service"))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

builder.Populate(services);
var container = builder.Build();
//Create the IServiceProvider based on the container.
return new AutofacServiceProvider(container);

UnitOfWork.cs

using System.Threading.Tasks;

namespace MakeTalk.Data.Infrastructure
{
public class UnitOfWork : IUnitOfWork
{
    #region Local variable

    private readonly IDatabaseFactory databaseFactory;
    private MakeTalkEntities dataContext;

    #endregion

    #region Constructor
    public UnitOfWork(IDatabaseFactory databaseFactory)
    {
        this.databaseFactory = databaseFactory;
    }
    #endregion

    #region Property
    protected MakeTalkEntities DataContext => dataContext ?? (dataContext = databaseFactory.Get());
    #endregion

    #region Methods
    /// <summary>
    /// Commit changes 
    /// </summary>
    /// <history>Created : 01-04-2018</history>
    public void Commit()
    {
        DataContext.SaveChanges();
    }
    /// <summary>
    /// Commit Async changes
    /// </summary>
    /// <returns></returns>
    /// <history>Created : 01-04-2018</history>
    public async Task<int> CommitAsync()
    {
        return await DataContext.SaveChangesAsync();
    }

    #endregion

}
}

Repository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;


namespace MakeTalk.Data.Infrastructure
{
    public class Repository<T> : IRepository<T> where T : class
    {
        #region Variable / Properties  
        private MakeTalkEntities dataContext;
        private readonly DbSet<T> dbSet;
        protected MakeTalkEntities DataContext => dataContext ?? (dataContext = DatabaseFactory.Get());
    protected IDatabaseFactory DatabaseFactory
    {
        get;
        private set;
    }
    #endregion

    #region Constructor
    protected Repository(IDatabaseFactory databaseFactory)
    {
        DatabaseFactory = databaseFactory;
        dbSet = DataContext.Set<T>();
    }
    #endregion

    #region Sync Methods

    // all methods ...
    #endregion
}
}

DatabaseFactory.cs

using Microsoft.EntityFrameworkCore;

namespace MakeTalk.Data.Infrastructure
{
    public class DatabaseFactory : Disposable, IDatabaseFactory
    {
        private MakeTalkEntities dataContext;

        public MakeTalkEntities Get()
        {
            return dataContext ?? (dataContext = new MakeTalkEntities(new DbContextOptions<MakeTalkEntities>()));
        }
        protected override void DisposeCore()
        {
            dataContext?.Dispose();
        }
    }
}

MakeTalkEntities.cs

using Microsoft.EntityFrameworkCore;
using MakeTalk.Data.Configuration;
using MakeTalk.Model;

namespace MakeTalk.Data
{
    public class MakeTalkEntities : DbContext
    {
        #region Constructor

        public MakeTalkEntities(DbContextOptions options)
        {

        }

        #endregion

        #region DB Properties 
        // db sets 

        #endregion

        #region Methods

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {


            // ReSharper disable once AssignNullToNotNullAttribute
            optionsBuilder.UseSqlServer("Some-Connection");

            base.OnConfiguring(optionsBuilder);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            // all configutaion 

            base.OnModelCreating(modelBuilder);
        }
        #endregion

    }
}

代碼有什么問題嗎? 我能解析我的其他存儲庫和服務,只是面臨Generic Repository builder.RegisterGeneric(typeof(Repository <>))的問題.As(typeof(IRepository <>))。InstancePerLifetimeScope();

在使用此通用存儲庫時,我收到以下錯誤

Autofac.Core.DependencyResolutionException:激活特定注冊期間發生錯誤。 有關詳細信息,請參閱內部異常 注冊:Activator = CommonService(ReflectionActivator),Services = [MakeTalk.Service.ICommonService],Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,Sharing = Shared,Ownership = OwnedByLifetimeScope --->在激活特定注冊期間發生錯誤。 有關詳細信息,請參閱內部異常 注冊:Activator = Repository 1 (ReflectionActivator), Services = [MakeTalk.Data.Infrastructure.IRepository 1 [[MakeTalk.Model.ExhibitionRequestStatus,MakeTalk.Model,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,Sharing = Shared,Ownership = OwnedByLifetimeScope --->沒有類型'MakeTalk.Data.Infrastructure.Repository 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = Repository 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = Repository 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. (See inner exception for details.) (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = Repository 1(ReflectionActivator),Services = [MakeTalk.Data.Infrastructure.IRepository 1[[MakeTalk.Model.ExhibitionRequestStatus, MakeTalk.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> No constructors on type 'MakeTalk.Data.Infrastructure.Repository 1 [MakeTalk.Model.ExhibitionRequestStatus]'的構造函數可以在構造函數查找器中找到' Autofac.Core.Activators.Reflection.DefaultConstructorFinder”。 (有關詳細信息,請參閱內部異常。)---> Autofac.Core.DependencyResolutionException: 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable類型'MakeTalk.Data.Infrastructure.Repository 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1[MakeTalk.Model.ExhibitionRequestStatus]' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'. at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1參數)在Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1 parameters) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable )中的Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id,Func 1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1 parameters) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1個參數) 1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1參數)位於Autofac的Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()中的Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext上下文,IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1參數)---內部異常堆棧跟蹤結束---在Autofac.Core.Resolving.InstanceLookup.Act ivate(IEnumerable 1 parameters) at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func 1創建者),Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope,在Autofac.ResolutionExtensions的Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文,服務服務,IEnumerable 1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable 1參數)中的1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable 1參數1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable Microsoft.AspNetCore的lambda_method(Closure,IServiceProvider,Object [])上的Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired)中的1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1參數) .Mvc.Controllers.ControllerActivatorProvider。< > c__DisplayClass4_0.b__0(ControllerContext controllerContext)at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider。<> c__DisplayClass5_0.g__CreateController | 0(ControllerContext controllerContext)at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&next,Scope&scope,Object&在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()中的Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()處於Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)中的state,Boolean&isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync中的Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State&next,Scope&scope,Object&state,Boolean&isCompleted)at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync ()Microsoft.AspNetCore.Routing.EndpointRoutingMi上的Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)中的ddleware.Invoke(HttpContext httpContext)

如果您查看錯誤消息,您可以看到這一點

使用構造函數查找器Autofac.Core.Activators.Reflection.DefaultConstructorFinder可以找到類型MakeTalk.Data.Infrastructure.Repository1[MakeTalk.Model.ExhibitionRequestStatus]上的構造Autofac.Core.Activators.Reflection.DefaultConstructorFinder

這意味着Autofac無法在Repository<T>類型上找到構造函數。 如果您查看此類型,構造函數將標記為protected ,這意味着Autofac無權訪問它。

要修復此錯誤,您必須將構造函數更改為public

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM