Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Susanne Hou 3 posts 73 karma points
    Oct 29, 2020 @ 16:40
    Susanne Hou
    0

    Compose - register class with constructor parameter

    I'm working on a solution that has a lot of legacy code, and one of the issues is how tight everything is coupled, and how impossible it is to write any form of unit tests. Anyway, I'm looking into what I can do to make it more loosly coupled, and came across the built-in dependency injection Umbraco has. I'm new to Umbraco, so bear with me. An example:

     composition.Register<FooBar>();
    

    This FooBar class has no parameterless constructor (in the current state the solution is in), and so this line does not work. I wonder if it is possible to register a class with a parameter attached to it - and if it is possible if FooBar has no interface. I'm think something along the lines of:

    composition.Register<FooBar>().WithParameters(Foo);
    

    We are using Umbraco v.8.6.1

  • Matthew Wise 257 posts 1182 karma points MVP c-trib
    Nov 03, 2020 @ 11:27
    Matthew Wise
    0

    Hi,

    If the parameters can also be registered dependency injection will handle that for you.

    If not you can use the factory method

    composition.Register<FooBar>(CreateFooBar);
    
    private static FooBarCreateFooBar(IFactory factory)
    {
         // var foo factory.GetInstance<Foo>() if its registered
         var foo = new Foo()
    
         return new FooBar(foo);
    }
    
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies