2012-02-21 108 views
4

我有一個使用Autofac和自定義成員資格提供程序的MVC3應用程序。如何使用Autofac注入asp.net mvc3自定義成員資格提供程序?

如果我嘗試使用ctor注入提供程序,則會出現錯誤:'沒有爲此對象定義無參數的構造函數。

public class MyMemberShipProvider : MembershipProvider 
    { 

     IUserRepository userRepository; 

    public MyMemberShipProvider(IUserRepository userRepository) 
     { 
      this.userRepository = userRepository; 

     } 
+0

你可以使用我的自定義會員供應商,照顧你的管道:http://blog.gauffin.org/2011/09/a-more-structured-membershipprovider/ – jgauffin 2012-02-21 14:00:00

+0

謝謝,很好的教程。 – tobias 2012-02-21 15:47:07

回答

7

您無法注入內置提供程序(Membership/Roles)。 您可以使用MVC 3 DependencyResolver和Autofac。

一個簡單的例子...

public override bool ValidateUser(string username, string password) 
{ 
    var userRepo = DependencyResolver.Current.GetService<IUserRepository>(); 
    return userRepo.ValidateUser(username, password); 
} 
+0

歡迎來到StackOverflow Neil - 好的答案 – petenelson 2012-02-21 14:00:21

+3

不幸的是,這然後是服務定位器反模式,請參閱:http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html – 2012-02-21 15:47:33

+1

它肯定是反模式,但如果您的約束是利用現有的ASP.NET成員資格提供程序,那麼您將面臨重寫所有成員資格和/或角色提供的內容,或引入此反模式。請注意,當替代方案可能需要大量工作時,反模式不會成功或失敗。 – CodeMonkeyKing 2012-12-05 23:35:15

-1

這是因爲你應該注入你的userRepository。例如:

protected override void Load(ContainerBuilder builder) 
{ 
    builder.RegisterType<UserRepository>().As<IUserReposotory>(); 
    builder.RegisterType<MyMembershipProvider>(); 
} 
+0

您確定MVC3支持成員資格提供程序的依賴注入嗎? – jgauffin 2012-02-21 13:56:51

+0

沒有propably不。尼爾有上面的答案。 – 2012-02-21 14:18:45

+0

在他的回答中內置了諸如@Neil提到的提供者,使用ASP.NET作爲頁面生命週期的一部分加載成員提供者。這早於MVC [1-4],也引入了IoC容器。 – CodeMonkeyKing 2012-12-05 23:32:49

1

避免在應用程序代碼中解決(驗證用戶,等等),因爲這是服務定位器的反模式。你只想解決你的'膠水'代碼/低級代碼。

這下面是windsor,但實施可以很容易地調整。這裏是城堡windsor的一個概述,但實施應該是類似的。它有點清潔劑,因爲這解決了呼叫GetProvider - 這是「膠水」代碼在這裏,從而避免在實際隸屬函數的服務定位器反模式的使用(如的ValidateUser)

http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html

相關問題