Dismissile
Dismissile

Reputation: 33071

Dependency injection for stateful services

I have a Service Fabric statefulservice that contains both a RunAsync loop and an OWIN Web API listener. Is it possible to add dependency injection into both the StatefulService inherited class and the API controllers? I have only really been able to get one or the other.

If I put the container logic in the Startup.cs then I can get DI easily for the Web API controllers, but not the stateful service.

If I put the container logic in Program.cs then I can get it for the stateful service but not the web api. (actually this feels more like service locator but I am okay with that in this instance)

Program.cs

private static void Main()
{
    var builder = new ContainerBuilder();

    builder.RegisterModule<MyModule>();

    var container = builder.Build();

    ILogger logger = container.Resolve<ILogger>();

    ServiceRuntime.RegisterServiceAsync("MyService", (context) => new MyService(context, logger)).GetAwaiter().GetResult();
}

Without passing in the IContainer to the StatefulService constructor I have no idea how I can get it to the Startup initialization for Web API to set the DependencyResolver.

Upvotes: 3

Views: 1509

Answers (1)

Nick Randell
Nick Randell

Reputation: 18295

I've got a solution where I create the container in the communication listener creation.

protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
    return new[] {
        new ServiceInstanceListener(CreateOwinCommunicationListener, "owin")
    };
}

private ICommunicationListener CreateOwinCommunicationListener(StatelessServiceContext context)
{
    var container = CreateContainer();
    return new OwinCommunicationListener("api", new Startup(container), context, Log, "WebServiceEndpoint");
}

If I want to access the container in the service I can also do that.

Upvotes: 4

Related Questions