我正在使用和MVC 5项目,我尝试设置我的应用程序的上下文,以便它使用身份上下文和应用程序域上下文作为一个上下文。我对依赖注入更新一点,我想我可能在某个地方犯了一个错误,导致这些错误无法正常工作。我已经看到很多答案,说明你只需要创建两个连接字符串,一个是实体框架连接字符串,另一个是sql连接字符串。然后将sql连接字符串传递给您的上下文,不知何故,MVC将知道使用哪一个。我认为这可能与我在每个请求应用程序数据库上下文中使用containercoped容器这一事实有关,但在删除容器范围约束时它仍然失败。
当我使用sql连接字符串时,我得到一个错误,说applicationUser不是当前上下文的一部分,但域对象似乎查询正常。当我使用我的实体框架连接字符串时,context.Users对象为空,表示标识内容不起作用。我哪里错了?如果您需要其他代码信息,请告诉我,我会发布。
<add name="DefaultConnection" connectionString="Data Source=HUNTER-PC;database=SteadyHOPS;integrated security=true;" providerName="System.Data.SqlClient" />
<add name="ApplicationDbContext" connectionString="metadata=res://*/Data.SteadyHOPS.ADO.csdl|res://*/Data.SteadyHOPS.ADO.ssdl|res://*/Data.SteadyHOPS.ADO.msl;provider=System.Data.SqlClient;provider connection string="data source=HUNTER-PC;initial catalog=SteadyHOPS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
public interface IApplicationDbContext {}
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
{
public ApplicationDbContext()
: base("name=DefaultConnection")
{
Database.SetInitializer<ApplicationDbContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// I put these lines here to resolve and error about not being able to resolve the key
modelBuilder.Entity<AspNetUserLogin>().HasKey(r => new { r.LoginProvider, r.ProviderKey, r.UserId });
modelBuilder.Entity<C__RefactorLog>().HasKey<Guid>(r => r.OperationKey);
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<C__RefactorLog> C__RefactorLog { get; set; }
public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
public virtual DbSet<Client> Clients { get; set; }
public virtual DbSet<FieldType> FieldTypes { get; set; }
public virtual DbSet<Form> Forms { get; set; }
public virtual DbSet<FormField> FormFields { get; set; }
public virtual DbSet<Log> Logs { get; set; }
public virtual DbSet<SubmittedFieldValue> SubmittedFieldValues { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<AuditTrail> AuditTrails { get; set; }
public virtual ObjectResult<usp_FieldTypes_GetAll_Result> usp_FieldTypes_GetAll()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_FieldTypes_GetAll_Result>("usp_FieldTypes_GetAll");
}
public virtual int usp_FormField_Delete(Nullable<int> formFieldID, Nullable<System.Guid> userID)
{
var formFieldIDParameter = formFieldID.HasValue ?
new ObjectParameter("FormFieldID", formFieldID) :
new ObjectParameter("FormFieldID", typeof(int));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("usp_FormField_Delete", formFieldIDParameter, userIDParameter);
}
public virtual ObjectResult<usp_FormField_GetAllByFormID_Result> usp_FormField_GetAllByFormID(Nullable<int> formID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_FormField_GetAllByFormID_Result>("usp_FormField_GetAllByFormID", formIDParameter);
}
public virtual ObjectResult<usp_FormField_Insert_Result> usp_FormField_Insert(Nullable<int> formID, string fieldType, string fieldName, Nullable<int> fieldOrder, string displayText, string listValues, Nullable<System.Guid> userID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
var fieldTypeParameter = fieldType != null ?
new ObjectParameter("FieldType", fieldType) :
new ObjectParameter("FieldType", typeof(string));
var fieldNameParameter = fieldName != null ?
new ObjectParameter("FieldName", fieldName) :
new ObjectParameter("FieldName", typeof(string));
var fieldOrderParameter = fieldOrder.HasValue ?
new ObjectParameter("FieldOrder", fieldOrder) :
new ObjectParameter("FieldOrder", typeof(int));
var displayTextParameter = displayText != null ?
new ObjectParameter("DisplayText", displayText) :
new ObjectParameter("DisplayText", typeof(string));
var listValuesParameter = listValues != null ?
new ObjectParameter("ListValues", listValues) :
new ObjectParameter("ListValues", typeof(string));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_FormField_Insert_Result>("usp_FormField_Insert", formIDParameter, fieldTypeParameter, fieldNameParameter, fieldOrderParameter, displayTextParameter, listValuesParameter, userIDParameter);
}
public virtual ObjectResult<usp_FormField_Update_Result> usp_FormField_Update(Nullable<int> formID, Nullable<int> formFieldID, string fieldType, string fieldName, Nullable<int> fieldOrder, string displayText, string listValues, Nullable<System.Guid> userID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
var formFieldIDParameter = formFieldID.HasValue ?
new ObjectParameter("FormFieldID", formFieldID) :
new ObjectParameter("FormFieldID", typeof(int));
var fieldTypeParameter = fieldType != null ?
new ObjectParameter("FieldType", fieldType) :
new ObjectParameter("FieldType", typeof(string));
var fieldNameParameter = fieldName != null ?
new ObjectParameter("FieldName", fieldName) :
new ObjectParameter("FieldName", typeof(string));
var fieldOrderParameter = fieldOrder.HasValue ?
new ObjectParameter("FieldOrder", fieldOrder) :
new ObjectParameter("FieldOrder", typeof(int));
var displayTextParameter = displayText != null ?
new ObjectParameter("DisplayText", displayText) :
new ObjectParameter("DisplayText", typeof(string));
var listValuesParameter = listValues != null ?
new ObjectParameter("ListValues", listValues) :
new ObjectParameter("ListValues", typeof(string));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_FormField_Update_Result>("usp_FormField_Update", formIDParameter, formFieldIDParameter, fieldTypeParameter, fieldNameParameter, fieldOrderParameter, displayTextParameter, listValuesParameter, userIDParameter);
}
public virtual int usp_Forms_Delete(Nullable<int> formID, Nullable<System.Guid> userID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("usp_Forms_Delete", formIDParameter, userIDParameter);
}
public virtual ObjectResult<usp_Forms_GetAll_Result> usp_Forms_GetAll()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_Forms_GetAll_Result>("usp_Forms_GetAll");
}
public virtual ObjectResult<usp_Forms_GetByID_Result> usp_Forms_GetByID(Nullable<int> formID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_Forms_GetByID_Result>("usp_Forms_GetByID", formIDParameter);
}
public virtual ObjectResult<usp_Forms_Insert_Result> usp_Forms_Insert(string formName, Nullable<int> clientID, Nullable<System.Guid> userID)
{
var formNameParameter = formName != null ?
new ObjectParameter("FormName", formName) :
new ObjectParameter("FormName", typeof(string));
var clientIDParameter = clientID.HasValue ?
new ObjectParameter("ClientID", clientID) :
new ObjectParameter("ClientID", typeof(int));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_Forms_Insert_Result>("usp_Forms_Insert", formNameParameter, clientIDParameter, userIDParameter);
}
public virtual ObjectResult<usp_Forms_Update_Result> usp_Forms_Update(Nullable<int> formID, string formName, Nullable<System.Guid> userID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
var formNameParameter = formName != null ?
new ObjectParameter("FormName", formName) :
new ObjectParameter("FormName", typeof(string));
var userIDParameter = userID.HasValue ?
new ObjectParameter("UserID", userID) :
new ObjectParameter("UserID", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_Forms_Update_Result>("usp_Forms_Update", formIDParameter, formNameParameter, userIDParameter);
}
public virtual int usp_Logs_Insert(string message, Nullable<System.DateTime> logDate, Nullable<int> clientID)
{
var messageParameter = message != null ?
new ObjectParameter("Message", message) :
new ObjectParameter("Message", typeof(string));
var logDateParameter = logDate.HasValue ?
new ObjectParameter("LogDate", logDate) :
new ObjectParameter("LogDate", typeof(System.DateTime));
var clientIDParameter = clientID.HasValue ?
new ObjectParameter("ClientID", clientID) :
new ObjectParameter("ClientID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("usp_Logs_Insert", messageParameter, logDateParameter, clientIDParameter);
}
public virtual int usp_SubmittedFieldValues_Insert(Nullable<int> formID)
{
var formIDParameter = formID.HasValue ?
new ObjectParameter("FormID", formID) :
new ObjectParameter("FormID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("usp_SubmittedFieldValues_Insert", formIDParameter);
}
}
结构图注册表
public class ApplicationDBContextRegistry : Registry
{
public ApplicationDBContextRegistry()
{
For<IApplicationDbContext>().Use<ApplicationDbContext>().ContainerScoped();
}
}
启动
[assembly: OwinStartupAttribute(typeof(SteadyHOPS.Startup))]
namespace SteadyHOPS
{
public partial class Startup
{
public IContainer Container
{
get
{
return (IContainer)HttpContext.Current.Items["_Container"];
}
set
{
if (HttpContext.Current.Items["_Container"] == null)
{
HttpContext.Current.Items["_Container"] = value;
}
}
}
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
DependencyResolver.SetResolver(
new StructureMapDependencyResolver(() => Container ?? IoC.Container));
IoC.Container.Configure(cfg =>
{
cfg.AddRegistry(new StandardRegistry());
cfg.AddRegistry(new ControllerRegistry());
cfg.AddRegistry(new ActionFilterRegistry(
() => Container ?? IoC.Container));
cfg.AddRegistry(new MvcRegistry());
cfg.AddRegistry(new TaskRegistry());
cfg.AddRegistry(new ModelMetadataRegistry());
cfg.AddRegistry(new ApplicationDBContextRegistry());
});
IoC.Container.Configure(cfg =>
{
cfg.AddRegistry(new DBContextRegistry(
() => Container ?? IoC.Container));
});
IoC.Container.Configure(cfg =>
{
cfg.AddRegistry(new IdentityRegistry(
() => Container ?? IoC.Container));
});
另一个相关的注册表
public class DBContextRegistry : Registry
{
public DBContextRegistry(Func<IContainer> _container)
{
var container = _container();
//ApplicationDbContext context = (ApplicationDbContext)container.GetInstance<IApplicationDbContext>();
For<DbContext>().Use((ApplicationDbContext)container.GetInstance<IApplicationDbContext>()).ContainerScoped();
}
}
身份登记
public class IdentityRegistry : Registry
{
public IdentityRegistry(Func<IContainer> _container)
{
var container = _container();
var args = new ExplicitArguments();
args.Set<DbContext>((ApplicationDbContext)container.GetInstance<IApplicationDbContext>());
//UserStore<ApplicationUser> store = (UserStore<ApplicationUser>)container.GetInstance<UserStore<ApplicationUser>>(args);
For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>().Use(() => new UserStore<ApplicationUser>((ApplicationDbContext)container.GetInstance<IApplicationDbContext>())).ContainerScoped();
//For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>().Use(container.GetInstance<UserStore<ApplicationUser>>(args)).ContainerScoped();
//For<IOwinContext>().Use();
For<Microsoft.Owin.Security.IAuthenticationManager>().Use(() => HttpContext.Current.GetOwinContext().Authentication).ContainerScoped();
For<IApplicationUserManager>().Use<ApplicationUserManager>().ContainerScoped(); //( UserStore<ApplicationUser>((ApplicationDbContext)container.GetInstance<IApplicationDbContext>())));
For<IApplicationSignInManager>().Use<ApplicationSignInManager>().ContainerScoped();
}
}
当前用户类
public class CurrentUser : ICurrentUser
{
private readonly IIdentity _identity;
private readonly ApplicationUserManager _manager;
private readonly ApplicationDbContext _context;
private ApplicationUser _user;
public CurrentUser(IIdentity identity, IApplicationUserManager manager, IApplicationDbContext context)
{
_identity = identity;
_manager = (ApplicationUserManager)manager;
_context = (ApplicationDbContext)context;
try
{
var test = _manager.Users.FirstOrDefault(); // this fails using the domain connection string but succeeds using identity one
var test2 = _context.Users.FirstOrDefault(); // this fails using the domain connection string but succeeds using identity one
}
catch (System.Exception e)
{
throw;
}
}
public ApplicationUser User
{
get { return _user ?? (_user = _manager.FindById(_identity.GetUserId())); }
}
}