1

我已閱讀和編碼示例如下:http://timschreiber.com/2015/01/14/persistence-ignorant-asp-net-identity-with-patterns-part-1/ 但該示例使用Unity的DI,但我使用Autofac的ID,當我嘗試運行我的項目我有以下錯誤:沒有發現的構造函數可以用可用的服務和參數調用Autofac

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'App.Front.Controllers.HomeController' can be invoked with the available services and parameters: Cannot resolve parameter 'Microsoft.AspNet.Identity.UserManager 2[IdentityStore.IdentityUser,System.Guid] userManager' of constructor 'Void .ctor(Microsoft.AspNet.Identity.UserManager 2[IdentityStore.IdentityUser,System.Guid])'.

我的代碼:

public class IdentityModule : Module 
{ 
    protected override void Load(ContainerBuilder builder) 
    { 
     //var dbContextParameter = new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(DbContext), 
     //            (pi, ctx) => ctx.Resolve<AppContext>()); 
     builder.RegisterType<UserStore>().As<IUserStore<IdentityUser, Guid>>().InstancePerLifetimeScope(); 
     builder.RegisterType<RoleStore>().InstancePerLifetimeScope(); 
    } 
} 

private static void SetAutofacContainer() 
{ 
    var builder = new ContainerBuilder(); 
    var mainModules = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(p => p.ManifestModule.Name.StartsWith("App.")).ToArray(); 
    builder.RegisterControllers(mainModules); 
    builder.RegisterAssemblyModules(mainModules); 

    builder.RegisterFilterProvider(); 
    builder.RegisterSource(new ViewRegistrationSource()); 

    builder.RegisterModule(new EFModule()); 
    builder.RegisterModule(new RepositoryModule()); 
    builder.RegisterModule(new IdentityModule()); 
    builder.RegisterModule(new ServiceModule()); 
    var container = builder.Build(); 
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 

} 

任何人都可以幫助我!

+0

我真的可以使用您用於通過AutoFac設置Identity的所有模塊。出於某種原因,我的實現遇到了同樣的問題,但我對AutoFac幾乎一無所知;特別是如何設置它。 –

回答

1

錯誤消息告訴您,Autofac無法創建HomeController的實例,因爲它無法找到其參數Microsoft.AspNet.Identity.UserManager<IdentityStore.IdentityUser,System.Guid> userManager

看來這種類型尚未註冊。要解決此錯誤,您必須註冊UserManager<IdentityUser, Guid>。您可以在您的IdentityModule類中執行此操作:

builder.RegisterType<UserManager<IdentityUser, Guid>>() 
     .As<UserManager<IdentityUser, Guid>>() 
     .InstancePerRequest(); 
+0

感謝你的幫助,我的代碼現在工作,但我想知道在這個例子中,他的代碼自定義UserStore類,如果我使用你的代碼,我的項目現在工作,但是當我創建和登錄用戶我的代碼有一個錯誤:[ InvalidOperationException:UserId not found。] 我的代碼登錄 var identity = await _userManager.CreateIdentityAsync(user,DefaultAuthenticationTypes.ApplicationCookie); –

+0

@TrườngSơn我不確定要理解。你能編輯你的問題並解釋你的問題嗎? –

+0

我遇到了同樣的問題,但實際上我使用的是MVC HTML5模板,它已經包含了AutoFac,並且沒有使用OP的模式。當我嘗試從@CyrilDurand包含解決方案時,它不起作用。完全陌生的DI,完全失去了。 –

相關問題