我想在ASP.NET MVC5项目中使用Autofac实现依赖注入。但我每次都收到以下错误:使用ASP.NET MVC配置Autofac 5
在App_Start夹建设者没有发现与类型“Autofac.Core.Activators.Reflection.DefaultConstructorFinder“MyProjectName.DAL.Repository` ........
我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 Configuration..Any帮助请??
什么是你的控制器类样子的构造?它取决于接口类型“IRepository”还是具体类型“Repository”?那么存储库类的构造函数是什么样的?请发布完整的示例。 –
@IanMercer问题已被编辑..请看现在.. – TanvirArjel
你在Autofac注册'SchoolContext'在哪里?如果没有(大概作为'PerHttpRequest'注册)它不能创建存储库。 –