开发者

Injecting a registered class using Autofac

I'm new to Autofac and trying to get things working for my first project using it. I'm not sure how inject the registered helper from Autofac? Any help would be appreciated.

App.xaml.cs

private void Application_Startup(object sender, StartupEventArgs e)
开发者_如何转开发{
    var builder = new ContainerBuilder();
    builder.Register(c => MyFactory.CreateHelper()).As<IHelper>();

    RootVisual = new MainWindow(...);
}

MainWindow.xaml.cs

public class MainWindow
{
   public IHelper IHelper {get;set;} 

   public MainWindow(IHelper helper)
   {
       iHelper = helper;
   }
}


You're 90% there, you were missing only one thing.

Add this to your Application_Startup in the App.xaml.cs

container = builder.Build();
RootVisual = new MainWindow(container.Resolve<IHelper>());

So now your Application_Statup would look like this, it will build your container and allow you to inject the registered classes with the container into your class(es). And make sure you properly dispose the container on Application_Exit.

IContainer container;
private void Application_Startup(object sender, StartupEventArgs e)
{
    var builder = new ContainerBuilder();
    builder.Register(c => MyFactory.CreateHelper()).As<IHelper>();

    container = builder.Build() 
    RootVisual = new MainWindow(container.Resolve<IHelper>());
}

private void Application_Exit(object sender, EventArgs e)
{
     container.Dispose();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜