Search code examples
entity-frameworkauthenticationasp.net-mvc-5decouple

how to seperate aspnet.identity.entityframework to its own assembly


I am trying to move the appicationDBContext out of the asp.net MVC5 web application project into its own assembly. i have tried creating a class library for the data access layer and using nuget to install the aspnet.identity assemblies.

I cannot get this to work. I have tried a few different examples but am not sure how is the best way to do this.

i have created a basic example in codeplex : https://testdal.codeplex.com/

this is an empty mvc5 website with a reference to a class library DAL. In DAL is the models from default sample website along with the references and some basic test code to try and register a user.

I get the following error :

Instance failure.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.InvalidOperationException: Instance failure.

Source Error:



Line 18:
Line 19:             var user = new ApplicationUser() { UserName = "paul" };
Line 20:             var result = UserManager.Create(user, "123456");
Line 21:
Line 22:


 Source File:  c:\Users\paul\Documents\Visual Studio 2013\Projects\emptyWebsite\DAL\Register.cs    Line:  20

Stack Trace:



[InvalidOperationException: Instance failure.]
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +414
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +196
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +146
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +16
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
   System.Data.SqlClient.SqlConnection.Open() +96
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<open>
    b__36(DbConnection t, DbConnectionInterceptionContext c) +36
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +138
    System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +477
    System.Data.Entity.SqlServer.<>c__DisplayClass34.<usingconnection>
        b__32() +344
        System.Data.Entity.SqlServer.<>c__DisplayClass1.<execute>
            b__0() +34
            System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +251
            System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +196
            System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +420
            System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +335
            System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +151
            System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +287
            System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +110
            System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +236
            System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +143
            System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +207
            System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +42
            System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +136
            System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +33
            System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext) +175
            System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +150
            System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +444
            System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +288
            System.Data.Entity.Internal.<>c__DisplayClassf`1.<createinitializationaction>
                b__e() +165
                System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +110
                System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +660
                System.Data.Entity.Internal.LazyInternalContext.<initializedatabase>
                    b__4(InternalContext c) +31
                    System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +143
                    System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +292
                    System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +123
                    System.Data.Entity.Internal.InternalContext.Initialize() +42
                    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +39
                    System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +137
                    System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path) +41
                    System.Data.Entity.Infrastructure.DbQuery`1.Include(String path) +142
                    System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, String path) +205
                    System.Data.Entity.QueryableExtensions.Include(IQueryable`1 source, Expression`1 path) +305
                    Microsoft.AspNet.Identity.EntityFramework.UserStore`6.GetUserAggregateAsync(Expression`1 filter) +610
                    Microsoft.AspNet.Identity.EntityFramework.UserStore`6.FindByNameAsync(String userName) +1069
                    Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName) +177
                    Microsoft.AspNet.Identity.<validateusername>
                        d__4.MoveNext() +803
                        System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
                        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
                        System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
                        Microsoft.AspNet.Identity.<validateasync>
                            d__0.MoveNext() +468
                            System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
                            System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
                            System.Runtime.CompilerServices.ConfiguredTaskAwaiter.GetResult() +24
                            Microsoft.AspNet.Identity.<createasync>
                                d__0.MoveNext() +846
                                System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
                                System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
                                System.Runtime.CompilerServices.ConfiguredTaskAwaiter.GetResult() +24
                                Microsoft.AspNet.Identity.<createasync>
                                    d__d.MoveNext() +1113
                                    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
                                    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
                                    System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
                                    Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +228
                                    Microsoft.AspNet.Identity.UserManagerExtensions.Create(UserManager`2 manager, TUser user, String password) +260
                                    DAL.Register.register() in c:\Users\paul\Documents\Visual Studio 2013\Projects\emptyWebsite\DAL\Register.cs:20
                                    emptyWebsite.Controllers.HomeController.Index() in c:\Users\paul\Documents\Visual Studio 2013\Projects\emptyWebsite\emptyWebsite\Controllers\HomeController.cs:20
                                    lambda_method(Closure , ControllerBase , Object[] ) +101
                                    System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
                                    System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
                                    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
                                    System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
                                    System.Web.Mvc.Async.AsyncControllerActionInvoker.<begininvokesynchronousactionmethod>
                                        b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
                                        System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
                                        System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
                                        System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
                                        System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
                                        System.Web.Mvc.Async.AsyncInvocationWithFilters.<invokeactionmethodfilterasynchronouslyrecursive>
                                            b__3c() +117
                                            System.Web.Mvc.Async.<>c__DisplayClass45.<invokeactionmethodfilterasynchronouslyrecursive>
                                                b__3e() +323
                                                System.Web.Mvc.Async.<>c__DisplayClass30.<begininvokeactionmethodwithfilters>
                                                    b__2f(IAsyncResult asyncResult) +44
                                                    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
                                                    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
                                                    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
                                                    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
                                                    System.Web.Mvc.Async.<>c__DisplayClass28.<begininvokeaction>
                                                        b__19() +72
                                                        System.Web.Mvc.Async.<>c__DisplayClass1e.<begininvokeaction>
                                                            b__1b(IAsyncResult asyncResult) +185
                                                            System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
                                                            System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
                                                            System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
                                                            System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
                                                            System.Web.Mvc.Controller.<beginexecutecore>
                                                                b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
                                                                System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
                                                                System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
                                                                System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
                                                                System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
                                                                System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
                                                                System.Web.Mvc.Controller.<beginexecute>
                                                                    b__15(IAsyncResult asyncResult, Controller controller) +39
                                                                    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
                                                                    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
                                                                    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
                                                                    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
                                                                    System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
                                                                    System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
                                                                    System.Web.Mvc.MvcHandler.<beginprocessrequest>
                                                                        b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
                                                                        System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
                                                                        System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
                                                                        System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
                                                                        System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
                                                                        System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
                                                                        System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
                                                                        System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514928
                                                                        System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Can anybody help me find a simple way to seperate the models from the UI project?

Thanks

Paul


Solution

  • i managed to get around this problem after trying the following :

    Moving ASP.NET Identity model to class library http://www.umbraworks.net/bl0g/rebuildall/2013/10/22/Moving_ASP_NET_Identity_model_into_another_assembly

    I did try this originally and and tried many similar ways although i found starting from fresh, deleting the database and specifying a specific db location helped. I have later thought that possibly turning on data migrations would have resolved the issue. This is still dependent on the connection string in the web.config so is not completely decoupled but otherwise seems to now work

    thanks