asp.net - Dependency Injection in service and for web application -
i use dependency injection business layer, contains services, such example 1 below:
public class myservice : imyservice { private imydbcontext dbcontext; public myservice(imydbcontext dbcontext) { this.dbcontext = dbcontext; } public dosomething(int id) { // use business layer var user = this.dbcontext.set<user>().find(id); } }
as can see, service has entity framework dbcontext dependency. using ninject ioc container, think apply any.
asp.net mvc website configuration
for asp.net website, have configured using ninject create single imydbcontext
per request , 1 instance of imyservice
required per request - it's nice , straightforward.
- imyservice - transient
- imydbcontext - per request
windows service configuration
i wish configure each iteration of window service, don't have 'new up' service every iteration.
i want have following configuration:
- imyservice - single instance or transient
- imydbcontext - new instance every time method called
the problem
how can achieved when sharing services between 2 different projects.
my friend suggested use factory idbcontext
, fine if didn't want continue using per request scope
within asp.net application - do. i'm not sure can configure factory return same instance every time purpose , new instance each request in windows service.
the problem is, example if use factory (for windows service requires new instance every call dosomething()
):
public class myservice : imyservice { private imycontextfactory dbcontextfactory; public myservice(imycontextfactory dbcontextfactory) { this.dbcontextfactory = dbcontextfactory; } public dosomething(int id) { // instance of db use var dbcontext = this.dbcontextfactory.getinstance(); // use business layer var user = dbcontext.set<user>().find(id); } }
as can see, i've had add line of code in make use of factory.
this no longer works website wants make use of single (per request) instance of dbcontext.
i need configuration work both scenarios i'm sharing code base.
i have boostrapper both projects configures kernel
bindings, it's how configure bindings different scenarios whilst sharing code base.
because mvc , windows service 2 different hosts, differing requirements on lifetime of injected dependencies, should have own ninject registrations. mvc define imyservice differently windows service host.
if not possible , have use same ninject registration code both of hosts, type of application can named discrimator create instance of imyservice.
kernel.bind<imyservice>().to<myservice>().named("mvc"); // add lifetime thingy kernel.bind<imyservice>().to<myservice>().named("windowsservice"); // add lifetime // usage var iammvc= kernel.get<imyservice>("mvc");
if ninject gets "mvc", set 1 way, , if gets "windowsservice", set differently.
option 1 preferred, since mvc , windows service have different execution contexts (http request n all) , easier control dependencies independently.
Comments
Post a Comment