gpt4 book ai didi

asp.net-mvc - 使用 ASP.NET MVC 5 配置 Autofac

转载 作者:行者123 更新时间:2023-12-04 18:02:55 26 4
gpt4 key购买 nike

我正在尝试在 ASP.NET MVC5 项目中使用 Autofac 实现依赖注入(inject)。但我每次都收到以下错误:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyProjectName.DAL.Repository` ........



我在 App_Start 文件夹中的 Autofac 配置代码如下:
public static class IocConfigurator
{
public static void ConfigureDependencyInjection()
{
var builder = new ContainerBuilder();

builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<Repository<Student>>().As<IRepository<Student>>();

IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}

在 Global.asax 文件中:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
// Other MVC setup

IocConfigurator.ConfigureDependencyInjection();
}
}

这是我的 IRepository:
public interface IRepository<TEntity> where TEntity: class 
{
IQueryable<TEntity> GelAllEntities();
TEntity GetById(object id);
void InsertEntity(TEntity entity);
void UpdateEntity(TEntity entity);
void DeleteEntity(object id);
void Save();
void Dispose();
}

这是我的存储库:
public class Repository<TEntity> : IRepository<TEntity>, IDisposable where TEntity : class
{
internal SchoolContext context;
internal DbSet<TEntity> dbSet;

public Repository(SchoolContext dbContext)
{
context = dbContext;
dbSet = context.Set<TEntity>();
}
.....................
}

这是我的学生 Controller :
public class StudentController : Controller
{

private readonly IRepository<Student> _studentRepository;
public StudentController()
{

}
public StudentController(IRepository<Student> studentRepository)
{
this._studentRepository = studentRepository;
}
....................
}

我的 Autofac 配置有什么问题..请帮忙?

最佳答案

要注入(inject)依赖项,您需要满足链下所有部分的所有依赖项。

在您的情况下,Repository没有 SchoolContext 就无法满足构造函数.

因此,在您的注册中添加:

  builder.RegisterType<SchoolContext>().InstancePerRequest();

http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request

关于asp.net-mvc - 使用 ASP.NET MVC 5 配置 Autofac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com