asp.net mvc and controller services architecture
I want to make my architecture better but i don't know how to resolve dependency trouble.
What i have:
- class library CoreService witch have a lot of interfaces
IMail
,Ilog
,ISession
- In app start i created
IMail
,Ilog
,ISession
based classes and pass it to CoreService class - base controller class with CoreService instance (prope开发者_开发技巧rty
CoreService Services {get;}
) - user plugin use CoreService interfaces
The problem: Every time i need to add new service i must edit app start, CoreService. Ideally I would like just create a class lib for IMail (or any other service) and register it in web.config or in app start.
I would appreciate for any advice or links that will help me.
Thanks for all so users!
Take a look at Ninject and XML configuration Binding.
I think this covers both parts of what you're aiming to achieve. This is dependency injection as well as being able to modify configuration without needing to recompile.
If you add entirely new services that Ninject (or other DI containers - Unity for example) isn't resolving for you, you will need to edit your code. I don't think that's avoidable.
What you need is a Dependency Injection framework to resolve your dependencies. DI frameworks will manage the creation and lifetime and disposing of objects.
builder.RegisterType<MySession>().As<ISession>().InstancePerHttpRequest();
builder.RegisterType<MyMail>().As<IMail>().Singleton();
Then you can use constructor injection to inject these
public class MyController : BaseController
{
public MyController(ISession session, IMail mail)
{
_session = session;
_mail = mail;
}
//other methods and member variables
}
This way you have to modify only one place when you need to add new dependencies.
精彩评论