我正在使用.net核心API,并使用autofac解决了我的依赖关系。但是以某种方式我无法解决我的通用存储库的依赖性。
有人可以指导我做错了什么。
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
}
}
代码有什么问题吗?我能够解决我的其他存储库和服务,而这些存储库和服务正面临通用存储库的问题 builder.RegisterGeneric(typeof(Repository <>))。As(typeof(IRepository <>))。InstancePerLifetimeScope();
在使用该通用存储库时,出现以下错误
Autofac.Core.DependencyResolutionException:激活特定注册期间发生错误。有关详细信息,请参见内部异常。注册:激活程序= CommonService(ReflectionActivator),服务= [MakeTalk.Service.ICommonService],生命周期= Autofac.Core.Lifetime.CurrentScopeLifetime,共享=共享,所有权= OwnedByLifetimeScope --->在激活特定注册时发生错误。有关详细信息,请参见内部异常。注册:激活程序=存储库
1 (ReflectionActivator), Services = [MakeTalk.Data.Infrastructure.IRepository
1 [[MakeTalk.Model.ExhibitionRequestStatus,MakeTalk.Model,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]],寿命= Autofac.Core.Lifetime.CurrentScopeLifetime,共享=共享,所有权= OwnedByLifetimeScope --->类型'MakeTalk.Data.Infrastructure.Repository1[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)上没有构造函数,服务= [MakeTalk.Data.Infrastructure.IRepository1[[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 [可以使用构造函数查找器“ Autofac.Core.Activators.Reflection.DefaultConstructorFinder”找到“ MakeTalk.Model.ExhibitionRequestStatus]”。 (有关详细信息,请参见内部异常。)---> Autofac.Core.DependencyResolutionException:类型'MakeTalk.Data.Infrastructure.Repository1[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(IEnumerable1 parameters) --- End of inner exception stack trace --- at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable
1个参数)处 在Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id,Func1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable
1个参数)处 在Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() 在Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext上下文,IEnumerable1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable
1个参数)处 ---内部异常堆栈跟踪的结尾--- 在Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters) at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func
1个创建者)处 在Autofac.Core.Resolving.InstanceLookup.Execute() 在Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope,IComponentRegistration注册,IEnumerable1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable
1个参数)处 在Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文,服务服务,IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable
1个参数)处 在Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,Boolean isDefaultParameterRequired) 在lambda_method(Closure,IServiceProvider,Object []) 在Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider。<> c__DisplayClass4_0.b__0(ControllerContext controllerContext) 在Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider。<> c__DisplayClass5_0.g__CreateController | 0(ControllerContext controllerContext)中。 在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和isCompleted)处 在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() 在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() 在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext上下文) 在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和已完成) 在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() 在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() 在Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) 在Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) 在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)
答案 0 :(得分:3)
如果查看错误消息,您将看到此
使用构造函数查找器
<Rectangle.OpacityMask> <LinearGradientBrush EndPoint="0.5,0" StartPoint="0.5,1"> <GradientStop Color="#00000000" Offset="0"/> <GradientStop Color="#FFFFFFFF" Offset="1"/> </LinearGradientBrush> </Rectangle.OpacityMask>
找不到类型MakeTalk.Data.Infrastructure.Repository1[MakeTalk.Model.ExhibitionRequestStatus]
的构造函数。
这意味着 Autofac 找不到类型为Autofac.Core.Activators.Reflection.DefaultConstructorFinder
的构造函数。如果您查看此类型,则构造函数将标记为Repository<T>
,这意味着 Autofac 无法访问它。
要解决此错误,您必须将构造函数更改为protected