我想在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'註冊)它不能創建存儲庫。 –