asp.net mvc - Inject repositories into service? -
i have following;
interface irepository --interface irepositoryef: irepository --interface irepositorynh: irepository ----interface icategoryrepositoryef: irepositoryef ----interface icategoryrepositorynh: irepositorynh
i want use categoryrepositoryef
, categoryrepositorynh
classes in service. how can inject them categoryservice?
categoryservice(irepository repository) { }
what best practice this? use repositoryfactory
, inject service , create repositories in services?
i mean following;
categoryservice(categoryrepositoryfactory factory) { var categoryrepositoryef = factory.create("ef"); var categoryrepositorynh = factory.create("nh"); }
is idea? or m wrong?
the idea bit off.
the purpose of repository interfaces abstract away data source. goal allow using classes fetch information without knowing data comes from. in case force classes know wether nhibernate or entityframework used. why?
i wouldn't have irepository
interface, create specific interfaces.
now question rather "how map nhibernate or entity framework repository 1 of interfaces".
that should done when application starts. typically this:
container.register<icategoryrepostitory, nhcategoryrepository>(); container.register<iuserrepostitory, efuserrepository>();
if don't have effectivly coupled using code specific implementation. there no need interfaces @ then.
update
which repository used if inject
categoryservice(icategoryrepository repository)
?
the repository registered in inversion of control container. point should not register both implementations 1 of them every repository.
a simple example below.
first manage repository type web.config:
<configuration> <appsettings> <add key="repositorytype" value="nhibernate" /> </appsettings> </configuration>
and when configure inversion of control container:
if (configurationmanager.appsettings["repositorytype"] == "nhibernate")) { _autofac.registertype<nhcategoryrepository>.as<icategoryrepository>(); _autofac.registertype<nhuserrepository>.as<iuserrepository>(); } else { _autofac.registertype<efcategoryrepository>.as<icategoryrepository>(); _autofac.registertype<efuserrepository>.as<iuserrepository>(); }
Comments
Post a Comment