Spring.Net注入实例化的windows服务?有可能吗?

时间:2016-08-29 20:49:47

标签: c# .net code-injection spring.net

我有一个使用顶层货架的Windows服务,以及我所拥有的主要服务方法,

static void Main(string[] args)
        {
            //TopShelf
            if (args != null && args.Length > 0)
            {
                var host = HostFactory.New(
                        x =>
                        {
                            x.Service<MyWindowsSvcHost>(
                                s =>
                                {
                                    s.ConstructUsing(name => new MyWindowsSvcHost());
                                    s.WhenStarted(tc => tc.Start(null));
                                    s.WhenStopped(tc => tc.Stop());
                                });
                            x.RunAsLocalSystem();
                            x.SetDescription("SomeServiceName");
                            x.SetDisplayName("SomeServiceName");
                            x.SetServiceName("SomeServiceName");

                        });
                host.Run();

                Environment.ExitCode = 0;
            }
            else
            {
                ServiceBase[] ServicesToRun = new ServiceBase[] { new MyWindowsSvcHost() };
                ServiceBase.Run(ServicesToRun);
            }
        }

我使用spring注入此服务的静态属性。在MyWindowsSvcHost里面,我有一个静态属性myStaticProperty,我想加载进去。以下是我的服务app.config的样子

<object id="SomeName" singleton="false" type="MyWindowsSvcHostAssembly.MyWindowsSvcHost, MyWindowsSvcHostAssembly">
        <property name="MyStaticProperty" ref="myStaticObject" />
      </object>

      <object id="myStaticObject" singleton="true" type="SomeAssembly.MyStaticClass, SomeAssembly">
      </object>

在服务中,我有财产

public static SomeClass MyStaticProperty {get;组; }

但这总是空的。如果我将下面的单例更改为true并调试它,它总是被正确分配,一切正常。

<object id="SomeName" singleton="true" type="MyWindowsSvcHostAssembly.MyWindowsSvcHost, MyWindowsSvcHostAssembly">
            <property name="MyStaticProperty" ref="myStaticObject" />
          </object>

知道幕后发生了什么吗?

1 个答案:

答案 0 :(得分:1)

对此的解决方案变得简单。当我开始服务时,

ServiceBase[] ServicesToRun = new ServiceBase[] { new MyWindowsSvcHost() };

我不得不将其解析为弹簧加载的实例,而不是创建新实例。