Unity Application Block, How pass a parameter to Injection Factory?

前端 未结 2 1265
悲&欢浪女
悲&欢浪女 2020-12-30 12:03

Here what I have now

  Container.RegisterType();
  Container.RegisterType(
                new I         


        
相关标签:
2条回答
  • 2020-12-30 12:42

    While most DI frameworks have advanced features to do these types of registrations, I personally rather change the design of my application to solve such a problem. This keeps my DI configuration simple and makes the code easier to understand. Especially for the creation of objects that depend on some context (thread, request, whatever) or have a lifetime that must be managed explicitly, I like to define factories. Factories make these things much more explicit.

    In your situation, you want to fetch a profile for a certain user. This is typically something you would like to have a factory for. Here's an example of this:

    // Definition
    public interface IProfileFactory
    {
        IProfile CreateProfileForUser(string username);
    }
    
    // Usage
    var profile = Container.Resolve<IProfileFactory>()
        .CreateProfileForUser("John");
    
    // Registration
    Container.RegisterType<IProfileFactory, ProfileFactory>();
    
    // Mock implementation
    public class ProfileFactory : IProfileFactory
    {
        public IProfile CreateProfileForUser(string username)
        {
            IUser user = Container.Resolve<IUserManager>()
                .GetUser(username);
    
            return new UserProfile(user);
        }
    }
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-30 12:49

    Resolve method allow passing parameters of ResolverOverride. Subtype of ResolverOverride is ParameterOverride which can be used to pass parameter to resolved constructor.

    You can do it this way (parameter is Name and passed value is John):

    Container.Resolve<IProfile>(new ParameterOverride("Name", "John"));
    
    0 讨论(0)
提交回复
热议问题