4
我正在使用wrapper for the ASP.NET Membership provider,以便我可以更鬆散地耦合使用該庫。我想要使用StructureMap來提供真正的IoC,但是我用配置用戶到配置文件工廠對象時遇到了麻煩,我正在使用該對象將配置文件實例化到用戶的上下文中。下面是相關的細節,首先從庫中的界面和包裝:使用StructureMap注入工廠方法
// From ASP.Net MVC Membership Starter Kit
public interface IProfileService
{
object this[string propertyName] { get; set; }
void SetPropertyValue(string propertyName, object propertyValue);
object GetPropertyValue(string propertyName);
void Save();
}
public class AspNetProfileBaseWrapper : IProfileService
{
public AspNetProfileBaseWrapper(string email) {}
// ...
}
接下來,在配置文件數據中的特定屬性進行交互的庫:在提供
class UserDataRepository : IUserDataRepository
{
Func<MembershipUser, IProfileService> _profileServiceFactory;
// takes the factory as a ctor param
// to configure it to the context of the given user
public UserDataRepository(
Func<MembershipUser, IProfileService> profileServiceFactory)
{
_profileServiceFactory = profileServiceFactory;
}
public object GetUserData(MembershipUser user)
{
// profile is used in context of a user like so:
var profile = _profileServiceFactory(user);
return profile.GetPropertyValue("UserData");
}
}
這是我第一次嘗試StructureMap註冊表配置,但它顯然是行不通的:
public class ProfileRegistry : Registry
{
public ProfileRegistry()
{
// doesn't work, still wants MembershipUser and a default ctor for AspNetProfileBaseWrapper
For<IProfileService>().Use<AspNetProfileBaseWrapper>();
}
}
從理論上講,我想如何註冊它看起來是這樣的:
// syntax failure :)
For<Func<MembershipUser, IProfileService>>()
.Use<u => new AspNetProfileBaseWrapper(u.Email)>();
...我可以在配置中定義工廠對象。這顯然是無效的語法。有沒有簡單的方法來完成這個?我是否應該使用其他模式來允許在用戶的上下文中構建UserDataRepository?謝謝!
+1幫了我,很高興,我發現這個。 – 2011-10-10 20:18:46
爲什麼這不在頂部的官方文檔中?!? – Yojin 2015-03-13 20:01:02