简体   繁体   中英

StructureMap to create a Configuration object in c# winforms

Using structuremap and c# 4.0 basically what i have is this:

interface IBoard
{
    void Setup();
}

class Board : IBoard
{
    IConfig _config;

    Board(IConfig config)
    {
        _config = config;
    }

    void Setup()
    {
        //use the _config object here 
    }
}

class Game
{
    IBoard _board;

    Game(IBoard board)
    {
        _board = board;
    }
}

partial class Form1
{
    Form1()
    {
        InitializeForm();
    }

    //in here we need to do some work to setup the IConfig object 
    //via form controls
}

partial class Form2
{
    Game _game;

    Form1(Game game)
    {
        InitializeForm();
        _game = game;
    }
}

now under normal usage id just say

For<Type>().Use<Class>() 

or thereabouts for all my dependancies. However what i am after is what is the best pattern to use to set the values of the config object in form1 and then call form2 with the config values set in memory and maintained throughout the app? i thought of using a singleton however the singleton should be imuttable or at least be statically created and not accept a parameter based config... so what to do? i currently create the form1 in the Program of the winform start up via

ObjectFactory.Get<Form1>();

I don't think that the IConfig is a good fit for creating using the container since you don't know the parameter values until it's time to instantiate it. I think you have to supply the configuration instance to the code that calls the container in order to fetch the form.

You can supply arguments to the container using the With method:

ObjectFactory.With<IConfig>(theConfig).GetInstance<Form2>();

You want to minimize calls to the container, preferably just one place in you application that wire up the rest of it during bootstrapping. An alternative is to register a Func, resolve that during bootstrap and use that to create an instance of the Form2.

Registration:

var formFactory = config => new Form2(config);
x.For<Func<IConfig, Form2>>().Use( () => formFactory);

Usage:

//Get the Func somehow, preferably as a ctor dependency in Form1
var form2Creator = ... 
var config = new Config({some parameters from Form1 here});
var form2 = form2Creator(config);

If you register your Config like this:

For(Of IConfig).Singleton.Use(Of Config)

It'll be singleton and StructureMap will take care of the rest.

Another approach is:

starting a unit of work and setting your values, do your job, and dispose UoW, but it's a little complicated and I have no idea if you need UoW or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM