I'm in a similar position, wanting to use heaps of the ServiceStack tools in a non-webby project. I agree that there is a ... slight lack in documentation for Funq
I have been using it in a legacy WinForms app, trying to avoid changing the original project (too much) and I add the new forms to a new project.
I added references to most of the ServiceStack libraries to most of my projects (manually because I'm doing this in .Net 3.5)
Here is the code in the winforms Program.cs
file; Note that the FunqContainer
is a public static property - I'm still not sure about that, but it gives access across the whole project to the FunqContainer
using System;
using System.Threading;
using System.Windows.Forms;
using Funq;
using MyApp.Utilities;
static class Program
{
public static Funq.Container FunqContainer { get; set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
FunqContainer = new Container();
FunqContainer.Init();
etc...
}
}
FunqContainer.Init()
is an extension method in my separate project for - you guessed it - initializing Funq
using System.Configuration; // Don't forget to ref System.Configuration.dll
using Funq;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.SqlServer;
namespace MyApp.Utilities
{
public static class FunqExtensions
{
public static void Init(this Container container)
{
//-------------------------------------------------------
// NB - I don't particularly like AutoWiring the public properties.
// Usually I want private stuff in the constructor)
//-------------------------------------------------------
var sqlServerConnectionString = ConfigurationManager.ConnectionStrings["HowdyCS"];
container.Register<IDbConnectionFactory>(
c => new OrmLiteConnectionFactory(
sqlServerConnectionString,
SqlServerOrmLiteDialectProvider.Instance));
container.Register<SomeForm>(
c => new SomeForm(
c.Resolve<IDbConnectionFactory>()
)
).ReusedWithin(ReuseScope.None);
}
}
}
I like using the lamda in the registration - it defers the construction of objects until they get resolved, rather than at registration time.
By default, the container stores the resolved object as a singleton, but if you have something that needs to be initialized every time it gets used ( ie user controls or winforms ) then use the .ReusedWithin(ReuseScope.None)
extension.
Where I need my SomeForm
(ie in a button click or whatever)
...
private void btnOpenSomeForm_Click(object sender, EventArgs e)
{
var myForm = Program.FunqContainer.Resolve<SomeForm>();
myForm.Show();
}
Check http://blogs.clariusconsulting.net/kzu/mab-containermodel-funq-a-transparent-container/ for more info
As an aside, this also works for VB.net when you put it through http://converter.telerik.com/