开发者

StructureMap with Windows Forms

开发者 https://www.devze.com 2023-04-10 15:55 出处:网络
I\'m used to work with StructureMap with Web Apps... but now, I\'m working on a Windows Forms project and I\'d like to use it, but I don\'t how to configure it.

I'm used to work with StructureMap with Web Apps... but now, I'm working on a Windows Forms project and I'd like to use it, but I don't how to configure it.

In web, I'd have a bootstrapper class that is invoked on A开发者_开发问答pplication_Start on Global.asax, but I don't know how to do the same on WinForms.

Thanks!


You can initialize the container in the static main method that starts your application. Then retrieve your form instances from the container, so that any necessary dependencies can be injected. You could still put the initialization code in a Bootstrapper.

static class Program
{
    [STAThread]
    static void Main()
    {
        ObjectFactory.Initialize(...);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(ObjectFactory.GetInstance<Form1>());
    }
}


For a Winforms application the counter part to Application_Start would be the main method that initializes the first Form.

When using ORM mappers with web applications you generally have the thumb rule of creating a data context/session per http request. For a Winforms application you tend to go for a context per operation or per form.


You'd structure the bootstrapping and IoC configuration in the same ways (though I'm not sure how you'd include the form classes themselves, I haven't worked with WinForms much). The only real difference that you'd need is when/where the initializer gets called. It just has to be in the startup of the application. For web applications, you do indeed call it from Application_Start. I think in WinForms apps it would be in the OnLoad event of the main form.

If you have a main method anywhere (similar to a console app) then that would work as well. This could be if the WinForms app was ported from a console app, for example.

0

精彩评论

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

关注公众号