Using Unity With Minimal Configuration

2019-02-10 03:36发布

问题:

At work, we use Unity a lot. It's great at it's job, but the more you use it, the more your configuration file grows, the more runtime issues increase and the more you have to recreate your unity configuration for each test project.

So we end up with a huge unity configuration section that has to be duplicated accross several projects and when it comes time to deploy, you end up having to track down dlls that you forgot to add references to, but you only discover these at runtime. Not fun.

I'm guessing someone has come across this issue and has a solution. Ideally, I would like to figure out how to configure Unity in a way that makes use of convention over configuration and reduces runtime issues (ie, huge configuration files). Anyone know of a good way to implement Unity with minimal configuration?

Edit: One thing: I have to stick with only using Unity. Can't really switch to Ninject, etc.

回答1:

Unity has a configuration API so it's pretty easy to write some auto-configuration code using reflection.

Several people have blogged about it here:

http://geekswithblogs.net/watsonjon/archive/2009/09/28/unity-convention-based-registration.aspx

http://geekswithblogs.net/brians/archive/2010/07/04/convention-based-registration-extension-for-the-microsoft-unity-ioc-container.aspx

Including this one with some framework code you can reuse:

http://thedersen.com/2011/02/20/convention-based-configuration-for-microsoft-unity/

This has been discussed on the Unity discussion board. The issue is that everyone wants different conventions. Look at the blog posts, writing your own seems pretty trivial.



回答2:

In unity 3.0 you can now do configuration by convention. This blog post explains it in more detail:

http://blogs.msdn.com/b/agile/archive/2013/03/12/unity-configuration-registration-by-convention.aspx