Using ServiceStack Funq IoC: how dependencies are injected?

c#, inversion-of-control, servicestack-bsd

Solution

You need to call `AutoWire` to have the container inject the dependancies. You can use it in your WinForm app like this:

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.

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.

Problem

I have WinForm application and I want to use ServiceStack dependency injection mechanism: ``` 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`. 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? And WinForm must have parameterless constructor. Rest of code: ``` private static void Main() { var appHost = new AppHost(); appHost.Init(); } public interface IAppApplicationContext { } public class AppApplicationContext : IAppApplicationContext { } ```

Original source