【问题标题】:Where to put my IoC Container configuration in Service Fabric Service?将我的 IoC 容器配置放在 Service Fabric 服务中的什么位置?
【发布时间】:2018-07-11 22:56:49
【问题描述】:

我正在考虑将 IoC 容器依赖项配置放在 Service 类的 RunAsync 方法下,但我有一种不好的感觉,这不是正确的去处..

Azure Service Fabric 服务中是否有任何约定可以放置此类配置而不会引起任何类型的冲突?

另外,你会在哪里进行 dispose 调用?

注意:我正在为此使用 Simple Injector,但其他 IoC 容器中的其他示例也应该这样做。

【问题讨论】:

    标签: c# ioc-container azure-service-fabric simple-injector


    【解决方案1】:

    您可以在 program.cs 的启动代码中创建您的 IoC 容器。当您注册一个服务时,您可以向它传递一个回调方法,该方法通过ServiceContext 传递。一旦您拥有ServiceContext,您就可以使用它来访问您的应用程序配置以获取连接字符串等。

    这是我用来创建 Ninject 内核的一些代码。

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

    【讨论】:

    • 如果我有多个服务怎么办?我将为每个服务执行此操作吗? (假设容器配置相同)
    • 是的。您必须为每项服务执行此操作。请注意,这会改变您使用 IoC 的方式:它不是跨整个应用程序的一个全局 IoC 容器,而是每个服务实例一个容器,具有全局配置。
    • ServiceKernel 需要包含哪个命名空间?
    • ServiceKernel 是我自己设计的一个类,它封装了一个 Ninject 内核(容器)。您应该根据您使用的任何 IoC 替换您自己的容器或容器包装器来替换 ServiceKernel。
    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 2023-03-09
    相关资源
    最近更新 更多