Implement factory method using StructureMap

I use the shell for the ASP.NET membership provider so that I can use the weaker use of the library. I want to use StructureMap to provide true IoC, but I'm having trouble setting it up with the User-to-Profile factory object that I use to create a profile instance in the user's context. Here is the relevant data, first the interface and the shell 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, the repository for interacting with a specific 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"); } } 

Here is my first attempt to provide the StructureMap registry configuration, but it obviously does not 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 would like to register this would look something like this:

 // syntax failure :) For<Func<MembershipUser, IProfileService>>() .Use<u => new AspNetProfileBaseWrapper(u.Email)>(); 

... where I can define a factory object in the configuration. This is clearly invalid syntax. Is there an easy way to do this? Should I use some other template to allow the creation of my UserDataRepository in the user context? Thanks!

+4
source share
1 answer

If I looked at overloads for use, I would find

 Use(Func<IContext> func); 

... which I can use as:

 For<IUserService>().Use(s => new AspNetMembershipProviderWrapper(Membership.Provider)); 
+15
source

Source: https://habr.com/ru/post/1314112/