注射用StructureMap一个工厂方法 [英] Injecting a factory method using StructureMap
问题描述
我使用的是包装ASP.NET成员提供,这样我可以有更松散耦合库的使用。我想用StructureMap提供真实的IoC,但我有麻烦与我使用的是把实例化的用户的上下文中的配置文件的用户对个人资料工厂对象配置它。下面是相关的细节,首先从库中的界面和包装:
I'm using a wrapper for the ASP.NET Membership provider so that I can have more loosely coupled usage of the library. I'm wanting to use StructureMap to provide true IoC, but I'm having trouble with configuring it with a User-to-Profile factory object that I'm using to put instantiate the profile in the context of a user. Here's the relevant details, first the interface and wrapper from the library:
// 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) {}
// ...
}
接着,对具有特定属性的描述文件数据进行交互的信息库:
Next, a repository for interacting with a particular property in the profile data:
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注册表配置的第一次尝试,但它显然是行不通的:
Here's my first attempt at providing a StructureMap registry config, but it obviously doesn't work:
public class ProfileRegistry : Registry
{
public ProfileRegistry()
{
// doesn't work, still wants MembershipUser and a default ctor for AspNetProfileBaseWrapper
For<IProfileService>().Use<AspNetProfileBaseWrapper>();
}
}
从理论上讲我想如何注册它看起来是这样的:
Theoretically how I'd like to register it would look something like:
// syntax failure :)
For<Func<MembershipUser, IProfileService>>()
.Use<u => new AspNetProfileBaseWrapper(u.Email)>();
...在那里我可以定义配置中的工厂对象。这显然不是有效的语法。有没有一种简单的方法来做到这一点?我应该使用一些其他的方式,使建设我UserDataRepository在用户的环境?谢谢!
...where I can define the factory object in the configuration. This is obviously not valid syntax. Is there an easy way to accomplish this? Should I be using some other pattern to allow constructing my UserDataRepository in the context of a user? Thanks!
推荐答案
如果我期待已久的重载使用,我会发现
If I had looked at the overloads for Use, I would have found
Use(Func<IContext> func);
......,我可以为使用:
...which I can use as:
For<IUserService>().Use(s =>
new AspNetMembershipProviderWrapper(Membership.Provider));
这篇关于注射用StructureMap一个工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!