简体   繁体   English

使用ServiceStack Funq IoC:如何注入依赖项?

[英]Using ServiceStack Funq IoC: how dependencies are injected?

I have WinForm application and I want to use ServiceStack dependency injection mechanism: 我有WinForm应用程序,我想使用ServiceStack依赖注入机制:

public class AppHost : AppHostBase
{
    public AppHost()
        : base("MyName", typeof(AppHost).Assembly)
    {
    }

    public override void Configure(Container container)
    {
        container.RegisterAutoWiredAs<AppApplicationContext, IAppApplicationContext>();
    }
}

Then in some form class use it: 然后在某个表单类中使用它:

public class SomeClass : AppBaseForm
{
    public IAppApplicationContext AppApplicationContext { get; set; }

    public SomeClass(IAppApplicationContext appApplicationContext)
    {
        AppApplicationContext = appApplicationContext;
    }

    public SomeClass()
    {
    }
}

But AppApplicationContext is always null . AppApplicationContext始终为null When in parameterless constructor I write: 在无参数构造函数中,我写道:

AppApplicationContext = AppHostBase.Resolve<IAppApplicationContext>();

then every thing is OK. 然后每件事都行。 But is this right way to do that? 但这是正确的方法吗? I mean AppApplicationContext should not be resolved by IoC automatically? 我的意思是IoC不应该自动解决AppApplicationContext? And WinForm must have parameterless constructor. 并且WinForm必须具有无参数构造函数。

Rest of code: 其余代码:

private static void Main()
{
    var appHost = new AppHost();
    appHost.Init();
}

public interface IAppApplicationContext
{
}

public class AppApplicationContext : IAppApplicationContext
{
}

You need to call AutoWire to have the container inject the dependancies. 您需要调用AutoWire让容器注入依赖项。 You can use it in your WinForm app like this: 您可以在WinForm应用程序中使用它,如下所示:

public class SomeClass : AppBaseForm
{
    public IAppApplicationContext AppApplicationContext { get; set; }

    public SomeClass()
    {
        // Tell the container to inject dependancies
        HostContext.Container.AutoWire(this);
    }
}

When you use a regular ServiceStack service, the AutoWire happens behind the scenes during the request pipeline when ServiceStack creates an instances of your Service. 当您使用常规ServiceStack服务时,当ServiceStack创建服务实例时, AutoWire会在请求管道期间发生在幕后。

I have created a fully working example here . 我在这里创建了一个完整的例子 Note: The demo is just a console application, not WinForms but it does shows the IoC being used outside of the ServiceStack service, and it works no differently. 注意:演示只是一个控制台应用程序,而不是WinForms,但它确实显示了在ServiceStack服务之外使用的IoC,它的工作方式没有区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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