Search code examples
c#dryioc

There is a way to register service which is given as implicit type and has constructor with more then one parameter of primitive type


I am using dryloc and want to register service which is given as implicit type and can has constructor (or it may has not) with more then one parameters of primitive types like string or int

I have tried the following


var container = new Container();

Type serviceType; // some service type
Type serviceKey; // some serviceKey
var param1 = "some param1";
var param2 = "some param2";

container.Register(serviceType, Reuse.ScopedTo(serviceKey: serviceKey), 
    made: Parameters.Of.Type(_=> param1));

Using this API i can specify only one parameter of primitive type to be injected in constructor of service but not more. I can not use factory delegate and other similar approaches since i do not know details about type of service.

There is any way to implement this scenario?

Update

I have resolved this problem using child scopes.

Some clarifications

  • My initial example wasn't fully correct. In fact parameters have different types so there is no ambiguity.

  • ServiceType could has constructor which requires param1 and param2 or may has constructor which doesn't require them

var container = new Container();

Type serviceType; // some service type
Type serviceKey; // some serviceKey
var param1 = "some param1";
var param2 = 5;

container.Register(serviceType, Reuse.ScopedTo(serviceKey: serviceKey));

////

// parent scope which is created outside
IResolverContext context; 


object service = null;

using (var scope = context.OpenScope("my-child-scope"))
{
   scope.UseInstance(param1);
   scope.UseInstance(param2);

   service = scope.Resolve(serviceType);
}


Solution

  • Either use parameter by name: Parameters.Of.Name(x, ...).Name(y, ...)

    Or the full blown Made.Of which accepts primitive constants (or any value via Arg.Index):

    Made.Of(() => new Blah(param1, param2, Arg.Of<RemainingParamTypeToInject>()))

    Update: the full example

    using System;
    using DryIoc;
    
    public class Program
    {
        public static void Main()
        {
            var container = new Container();
    
            // variant 1
            container.RegisterInstance("1", serviceKey: "x");
            container.RegisterInstance("2", serviceKey: "y");
            container.Register<A>(made: Parameters.Of.Name("x", serviceKey: "x").Name("y", serviceKey: "y"));
    
            // variant 2
            //container.Register<A>(made: Parameters.Of.Name("x", _ => "1").Name("y", _ => "2"));
    
            var a = container.Resolve<A>();
    
            Console.WriteLine(a.X + ", " + a.Y);
        }
    
        public class A 
        {
            public string X, Y;
            public A(string x, string y) 
            {
                X = x;
                Y = y;
            }
        }
    }