Search code examples
c#owin

C# Pass objects to ApiController in Owin host


I have a Windows service that does some stuff on timer ticks. Now I need to add an API endpoint to this service to do almost the same stuff, but on-demand. In my service I have two instances of helper classes:

LithiumUtility lu;
MarketoUtility mu;

To host my endpoint I use Microsoft.AspNet.WebApi.OwinSelfHost package. I start it with IDisposable _server = WebApp.Start<Startup>(url: baseAddress); as seen in all tutorials. Startup class is nothing special as well.

My endpoint is defined in the following class:

public class MarketoController : ApiController{}

So, is there a way to pass my mu and lu to MarketoController. I would think that it should be done through a constructor, but MarketoController is not referred explicitly anywhere and I am not sure how it is even created.


Solution

  • After a lot of searching, I could not find an answer on "How can I use a concrete instance of some class". At least without installing 10 additional packages and writing 100 lines of code.

    So I went with this dirty approach:

    I created this class:

       struct UtilityClasses
    {
        public class1 c1 { get; set; }
        public class2 c2 { get; set; }
    
        public static UtilityClasses uc { get; set; }
        public UtilityClasses(class1 c1, class2 c2)
        {
            this.c1 = c1;
            this.c2 = c2;
        }
    }
    

    Near the line that starts the server IDisposable _server = WebApp.Start<Startup>(url: baseAddress), I call

            UtilityClasses uc = new UtilityClasses(c1, c2);
            UtilityClasses.uc = uc;
    

    and from my controller, I call

        private class1 c1;
        private class2 c2;
    
    
        public MarketoController()
        {
            c1 = UtilityClasses.uc.c1;
            c2 = UtilityClasses.uc.c2;
        }
    

    According to all I've read this is not a good idea, but it solves my issue.