我正在尝试在ASP.NET MVC5项目中使用Autofac实现依赖注入。但我每次都会收到以下错误:
在'MyProjectName.DAL.Repository`类型的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'中找不到任何构造函数........
我在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>();
}
.....................
}
这是我的学生管理员:
public class StudentController : Controller
{
private readonly IRepository<Student> _studentRepository;
public StudentController()
{
}
public StudentController(IRepository<Student> studentRepository)
{
this._studentRepository = studentRepository;
}
....................
}
我的Autofac配置出了什么问题。有任何帮助吗??
答案 0 :(得分:3)
要注入依赖关系,您需要满足链中所有部分的所有依赖关系。
在您的情况下,如果没有Repository
,则无法满足SchoolContext
构造函数。
所以在你的注册中添加:
builder.RegisterType<SchoolContext>().InstancePerRequest();
请参阅http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request