我正在使用通用接口
public interface IRepository<T> where T :class
{
List<T> GetAllRecords();
}
我还实现了一个通用存储库
public class BaseRepository<T> : IRepository<T> where T : class
{
protected readonly DataContext context;
public BaseRepository(DataContext data)
{
context = data;
}
public List<T> GetAllRecords()
{
return context.Set<T>().AsNoTracking().ToList();
}
}
DataContext - 数据库上下文。
创建了一个将扩展基本接口的接口
public interface IUserRepository : IRepository<User>
{
void MyMethod();
}
public class UserRepository : BaseRepository<User>, IUserRepository
{
protected readonly DataContext context;
protected readonly IUserRepository repository;
public UserRepository(DataContext data, IUserRepository user):base (data)
{
context = data;
repository = user;
}
public void MyMethod()
{
throw new NotImplementedException();
}
Autofac 配置文件
public class AutofacRegister
{
public static void ConfigureContainer()
{
// получаем экземпляр контейнера
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
// Register your Web API controllers.
// builder.RegisterType<DataContext>();
builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerRequest();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Set the dependency resolver to be Autofac.
var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;
}
}
向 GlobalAsax 添加了一行代码
AutofacRegister.ConfigureContainer();
在控制器中。
public class UserController : ApiController
{
IUserRepository repository;
public UserController(IUserRepository user)
{
repository = user;
}
public List<User> GetRecords()
{
return repository.GetAllRecords();
}
}
错误是什么,我理解依赖注入,但我做不到。使用通用存储库时我做错了什么?
取消注释该行
UserRepository
Autofac 在创建时对您的 DataContext 一无所知