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

Tom*_*ito 4 c# inversion-of-control servicestack-bsd

我有WinForm应用程序,我想使用ServiceStack依赖注入机制:

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

    public override void Configure(Container container)
    {
        container.RegisterAutoWiredAs<AppApplicationContext, IAppApplicationContext>();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在某个表单类中使用它:

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

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

    public SomeClass()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

AppApplicationContext总是如此null.在无参数构造函数中,我写道:

AppApplicationContext = AppHostBase.Resolve<IAppApplicationContext>();
Run Code Online (Sandbox Code Playgroud)

然后每件事都行.但这是正确的方法吗?我的意思是IoC不应该自动解决AppApplicationContext?并且WinForm必须具有无参数构造函数.

其余代码:

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

public interface IAppApplicationContext
{
}

public class AppApplicationContext : IAppApplicationContext
{
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*ott 8

您需要调用AutoWire容器注入依赖项.您可以在WinForm应用程序中使用它,如下所示:

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

    public SomeClass()
    {
        // Tell the container to inject dependancies
        HostContext.Container.AutoWire(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

当您使用常规ServiceStack服务时,AutoWire当ServiceStack创建服务实例时,会在请求管道期间在幕后发生.

我在这里创建了一个完整的例子.注意:演示只是一个控制台应用程序,而不是WinForms,但它确实显示了在ServiceStack服务之外使用的IoC,它的工作方式没有区别.