我有一个webapi项目,我使用Autofac
进行依赖注入。问题是我无法弄清楚如何注册UserManager类。它抛出了错误"{The entity type ApplicationUser is not part of the model for the current context.} System.InvalidOperationException"
。
请帮忙。
在AutofacConfig.Configure()中:
builder.RegisterType<ApplicationDbContext>().As<IApplicationDbContext>().InstancePerRequest()
builder.RegisterType<UserManager<ApplicationUser>>().InstancePerRequest();
builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
这就是我使用它的方式:
public class UsersRepository : IUsersRepository<ApplicationUser>
{
public IApplicationDbContext DbInstance { get; }
private UserManager<ApplicationUser> _userManager;
private IUserStore<ApplicationUser> _userStore;
public UsersRepository(IApplicationDbContext dbInstance, UserManager<ApplicationUser> userManager, IUserStore<ApplicationUser> userStore)
{
DbInstance = dbInstance;
_userManager = userManager;
_userStore = userStore;
}
public void Create(ApplicationUser user)
{
_userManager.Create(user);
DbInstance.SaveChanges();
}
}
IUsersRepository:
public interface IUsersRepository<T> where T : class
{
IApplicationDbContext DbInstance { get; }
void Create(T model);
void Update(string id, T model);
void Delete(string id);
List<T> GetAll();
T Get(string id);
}
我尝试了这个解决方案:https://gist.github.com/danielok/9271691但是在第一次调用用户时遇到了另一个错误webapi controller "ApplicationDbContext is not registered."
消息:
The requested service 'ToDoApp_Data.DbContext.ApplicationDbContext' has not been registered. To avoid this exception, either register a component to provide
the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
堆栈追踪:
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)
at ToDoApp_Api.App_Start.AutofacConfig.<>c.<RegisterOthers>b__4_1(ParameterInfo pi, IComponentContext ctx) in D:\Dev\ToDoApp_Backend\ToDoApp_Api\App_Start\AutofacConfig.cs:line 58
at Autofac.Core.ResolvedParameter.<>c__DisplayClass3_0.<CanSupplyValue>b__0()
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
P.S。我认为告诉我有其他webapi控制器,我设法使它们与autofac一起使用会很有用,但考虑到在使用DI之前,它实例化如下:UserManager _userManager = new UserManager(new UserStore(new ApplicationDbContext())); 。我不知道如何注册。