简体   繁体   中英

Where to put my IoC Container configuration in Service Fabric Service?

I was thinking in placing the IoC Container dependencies configuration under RunAsync method in the Service class but I have a bad feeling that's not the right place to go..

Is there any convention in Azure Service Fabric Services to place this type of configurations without causing any sort of conflicts?

Also, where would you place the dispose call?

Note: I'm using Simple Injector for this but other examples from other IoC containers should do too.

You can create your IoC container in the startup code in program.cs. When you register a service, you can pass it a callback method that is passed the ServiceContext . Once you have the ServiceContext , you can use it to gain access to your application configuration for connection strings and such.

Here's some code I use to create a Ninject kernel.

namespace AccountCommandService
{
    internal static class Program
    {
        private static void Main()
        {
            try
            {
                ServiceRuntime.RegisterServiceAsync("AccountCommandServiceType",
                    context =>
                    {
                        // Create IoC container
                        var kernel = new ServiceKernel(context);

                        // Create Service
                        return new AccountCommandService(context, 
                            kernel.Get<IAccountDataContextFactory>(), // Pull a DBContext factory from the IoC
                            );
                    }).GetAwaiter().GetResult();

                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
                throw;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM