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

拥有回忆 提交于 2019-12-11 02:45:39

问题


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.


回答1:


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;
            }
        }
    }
}


来源:https://stackoverflow.com/questions/48565765/where-to-put-my-ioc-container-configuration-in-service-fabric-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!