During the life of my web application I know all of my services and repositories will be called. I would like to instantiate them once during the startup of the web application and refer to the instantiated references in my code.
Is there a common pattern for instantiating your services/repositories only once during the lifetime of a web application without making them static or singletons.
I would like to avoid making my services/repositories static classes or singletons for testability however instantiating them on every web request do开发者_如何学Cesn't seem right when they are designed to be stateless and I know they will all be needed during the lifetime of the application.
I am using c#/asp.net.
The concept you need is called IoC / DI, and there are many frameworks for this. When you have a class like CustomerService and you need a CustomerRepository in it, by definition that is a dependancy, and you should pass it through the constructor of CustomerService - but then there is the question where you will instantiate CustomerService? Well, who uses that service should get it through constuctor too, it is maybe a CustomerPresenter, or some other class, irrelevant. My point is that with doing dependancy injections you structure your code to a very single point where an IoC / DI framework resolves those dependancies accoring to your rules.
At the very top of the program, you would have something like:
ICustomerPresenter presenter = IoC.Resolve<ICustomerPresenter>();
and everything will automatically come together behind the scenes.
To achieve this, here is an example with StructureMap:
For<ICustomerPresenter>().Use<CustomerPresenter>();
For<ICustomerService>().Singleton().Use<CustomerService();
For<ICustomerRepository>().Singleton().Use<CustomerRepository>();
With this, you keep the testability. I've simplified things a lot here, so this isn't much usable as-is, but there are plenty IoC / DI resources online, so check them out.
Note: for web applications you will want to check out handling lifecycle per request, you will rarely have singletons for entire web application.
Dependency Injection frameworks will take care of the lifetime of your objects.
Eg
container.RegisterType<MyService>().Singleton();
There are many DI frameworks choose what suits you best.
精彩评论