开发者

ASP.NET MVC Configuration Class using IoC

In an MVC app, we the have need to create a configuration settings class that is needed throughout the app. It is a cross-cutting concern in that it is need in controllers, sometimes deep in the domain logic, as well as place like HtmlHelper extensions. The fact that it's needed is so many different places is what is tripping me up.

The class will wrap settings that are pulled from the web.config, as well as a table in a DB. The DB settings query will be cached so I'm not worried about that getting h开发者_如何学编程it up for every request.

In years past I may have created some static type of class or singleton, but I don't want to lose the testability I have now. What would be the best way to instantiate this class and then to be able to access it through pretty much anywhere in the app?


I would continue to use a singleton. But a singleton which is wrapping an interface, which also makes it testable.

public class Configuration
{
    private IConfiguration _config;

    public static IConfiguration Instance { get { return _config; }}

    public static void Assign(IConfiguration config)
    {
       _config = config;
    }
}

Simply use Assign in global.asax or any of your unit tests.

If you want to do it the correct way, you should provide the configuration settings directly in the constructors of your objects.

Instead of

public class MyService
{
    public MyService()
    {
        var confString = Configuration.Instance.GetConnectionString()
    }
}

You would do:

public class MyService
{
    public MyService(string confString)
    {}
}

Finally, I would not have any configuration dependencies in HTML helpers. By doing so yuo are adding business logic to your views which breaks separation of concerns


I think the codeplex project mvccontrib provided some hooks to use at least 3 IOC providers as far as I not windsor, structurmap, spring.net... but I did not used it myself you can find out more here http://mvccontrib.codeplex.com/

and maybe you can look into the sourcecode of this project and see where you can go from there...

HTH


I would refactor my app not to use configuration everywhere. I use configuration in controllers only. My views do not have any logic, my domain model does just have business logic, not application logic.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜