title: Asp.net MVC4, PostgreSQL and SimpleMembership
body: <p>I use Npgsql 2.1 and EntityFramework 6.0 to work with PostgreSQL (Code First).
  All works fine. Here is the part of my Web.config:</p>
  
  <pre><code>&lt;configuration&gt;
    &lt;configSections&gt;
  //---
    &lt;connectionStrings&gt;  
      &lt;add name="MovieDBContext" connectionString="Server=127.0.0.1;Port=5432;Database=postgres;User Id=postgres;Password=123;" 
           providerName="Npgsql" /&gt;    
    &lt;/connectionStrings&gt;
  //---
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="Npgsql.NpgsqlFactory, Npgsql" /&gt;
      &lt;providers&gt;
        &lt;provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, Npgsql.EntityFramework"&gt;&lt;/provider&gt;
      &lt;/providers&gt;
    &lt;/entityFramework&gt;
    &lt;system.data&gt;
      &lt;DbProviderFactories&gt;
        &lt;remove invariant="Npgsql" /&gt;
        &lt;add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql" 
  type="Npgsql.NpgsqlFactory, Npgsql" /&gt;
      &lt;/DbProviderFactories&gt;
    &lt;/system.data&gt;  
  &lt;/configuration&gt;
  </code></pre>
  
  <p>All works fine with 10 related tables. But now I need authorization. </p>
  
  <p>Of course I read the post
  <a href="https://stackoverflow.com/questions/17830693/postgresql-npgsql-connector-mvc-and-simplemembership-not-working">PostgreSQL + Npgsql connector + MVC and SimpleMembership Not working</a>
  where Francisco Junior recommends to use Daniel Nauck's AspSQLProvider.</p>
  
  <p>I installed NauckIT.PostgreSQLProvider.2.0.0 from NuGet.
  Executed the script from the package to create the set of tables for it.
  Added this part of configuration info to Web.config:</p>
  
  <pre><code> &lt;system.web&gt;
      &lt;compilation debug="true" targetFramework="4.5" /&gt;
      &lt;httpRuntime targetFramework="4.5" /&gt;
  
      &lt;authentication mode="Forms"&gt;
        &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt;
      &lt;/authentication&gt;
  
      &lt;machineKey validationKey="518A9D0E650ACE4CB22A35DA4563315098A96D0BB8E357531C7065D032099214A11D1CA074B6D66FF0836B35CEAAD0E7EEEFAED772754832E0A5F94EF8522222"
          decryptionKey="DB5660C109E9EC70F044BA1FED99DE0C5922321C5125E84C23A1B5CA0E426909"
          validation="SHA1" decryption="AES" /&gt;
  
      &lt;membership defaultProvider="PgMembershipProvider"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="MovieDBContext" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" passwordFormat="Hashed" applicationName="MvcMovie"/&gt;
        &lt;/providers&gt;
      &lt;/membership&gt;
  
      &lt;roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="MovieDBContext" applicationName="MvcMovie"/&gt;
        &lt;/providers&gt;
      &lt;/roleManager&gt;
  
      &lt;profile enabled="true" defaultProvider="PgProfileProvider"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="MovieDBContext" applicationName="MvcMovie"/&gt;
        &lt;/providers&gt;
        &lt;properties&gt;
          &lt;add name="FirstName"/&gt;
          &lt;add name="LastName"/&gt;
        &lt;/properties&gt;
      &lt;/profile&gt;
  
      &lt;sessionState    mode="Custom"    customProvider="PgSessionStateStoreProvider"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="MovieDBContext" applicationName="MvcMovie" /&gt;
        &lt;/providers&gt;
      &lt;/sessionState&gt;
  </code></pre>
  
  <p>And got the error when tried to run:</p>
  
  <pre><code>Parser Error Message: This method cannot be called during the application's pre-start initialization phase.
  Source Error: 
  &lt;providers&gt;
  &lt;clear/&gt;
  &lt;add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="MovieDBContext" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" passwordFormat="Hashed" applicationName="MvcMovie"/&gt;
  &lt;/providers&gt;
  &lt;/membership&gt;
  </code></pre>
  
  <p>Tried to find anything about this error. 
  Follow this recommendation
  <a href="https://stackoverflow.com/questions/12049926/asp-net-4-5-custom-membership-provider-configuration-throws-strange-exception">asp.net 4.5 custom membership provider configuration throws strange exception</a>
  I add this to Web.config</p>
  
  <pre><code>  &lt;appSettings&gt;
  //---
      &lt;add key="enableSimpleMembership" value="false"/&gt;
      &lt;add key="autoFormsAuthentication" value="false"/&gt;
  </code></pre>
  
  <p>Now the application can run because the SimpleMembership is disabled. 
  By the way, trying to register user I get the next error</p>
  
  <pre><code>System.Reflection.TargetInvocationException was unhandled by user code
    HResult=-2146232828
    Message=Exception has been thrown by the target of an invocation.
    Source=mscorlib
    StackTrace:
         at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&amp; canBeCached, RuntimeMethodHandleInternal&amp; ctor, Boolean&amp; bNeedSecurityCheck)
         at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark)
         at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark&amp; stackMark)
         at System.Activator.CreateInstance(Type type, Boolean nonPublic)
         at System.Activator.CreateInstance(Type type)
         at System.Threading.LazyHelpers`1.ActivatorFactorySelector()
         at System.Threading.LazyInitializer.EnsureInitializedCore[T](T&amp; target, Boolean&amp; initialized, Object&amp; syncLock, Func`1 valueFactory)
         at System.Threading.LazyInitializer.EnsureInitialized[T](T&amp; target, Boolean&amp; initialized, Object&amp; syncLock)
         at MvcMovie.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in d:\Projects\_Npg\MvcMovieSln\MvcMovie\Filters\InitializeSimpleMembershipAttribute.cs:line 22
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain)
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.&lt;&gt;c__DisplayClass37.&lt;&gt;c__DisplayClass39.&lt;&gt;c__DisplayClass3b.&lt;BeginInvokeActionMethodWithFilters&gt;b__35()
         at System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain)
    InnerException: System.InvalidOperationException
         HResult=-2146233079
         Message=The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588
         Source=MvcMovie
         StackTrace:
              at MvcMovie.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() in d:\Projects\_Npg\MvcMovieSln\MvcMovie\Filters\InitializeSimpleMembershipAttribute.cs:line 46
         InnerException: System.InvalidOperationException
              HResult=-2146233079
              Message=Failed to set Database.DefaultConnectionFactory to an instance of the 'Npgsql.NpgsqlFactory, Npgsql' type as specified in the application configuration. See inner exception for details.
              Source=EntityFramework
              StackTrace:
                   at System.Data.Entity.Internal.AppConfig.&lt;.ctor&gt;b__3()
                   at System.Lazy`1.CreateValue()
                   at System.Lazy`1.LazyInitValue()
                   at System.Lazy`1.get_Value()
                   at System.Data.Entity.Internal.AppConfig.TryGetDefaultConnectionFactory()
                   at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
                   at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.&lt;&gt;c__DisplayClass1.&lt;GetService&gt;b__0(Tuple`2 t)
                   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
                   at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
                   at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.&lt;&gt;c__DisplayClass3.&lt;GetService&gt;b__0(IDbDependencyResolver r)
                   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
                   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
                   at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
                   at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
                   at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver)
                   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
                   at System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName()
                   at System.Data.Entity.Internal.LazyInternalContext.get_ProviderName()
                   at System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context)
                   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
                   at System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps()
                   at System.Data.Entity.Database.Exists()
                   at MvcMovie.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() in d:\Projects\_Npg\MvcMovieSln\MvcMovie\Filters\InitializeSimpleMembershipAttribute.cs:line 35
              InnerException: System.MissingMethodException
                   HResult=-2146233069
                   Message=Constructor on type 'Npgsql.NpgsqlFactory' not found.
                   Source=mscorlib
                   StackTrace:
                        at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark&amp; stackMark)
                        at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
                        at System.Activator.CreateInstance(Type type, Object[] args)
                        at System.Data.Entity.Internal.AppConfig.&lt;.ctor&gt;b__3()
                   InnerException: 
  </code></pre>
  
  <p>in the </p>
  
  <pre><code>LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
  </code></pre>
  
  <p>in the class</p>
  
  <pre><code>InitializeSimpleMembershipAttribute
  </code></pre>
  
  <p>Please help to configure Daniel Nauck's AspSQLProvider and InitializeSimpleMembershipAttribute (if needed).</p>
  
  <p>Thank you!</p>