ASP.NET BoilerPlate: How do I inject object of DbContext in application service?

亡梦爱人 提交于 2020-12-06 15:57:16

问题


How do I inject object of DbContext in application service?

Need to access it to create clone of a entity record.


回答1:


You can use IDbContextProvider<TDbContext> _sampleDbContextProvider as constructor injection, using with _sampleDbContextProvider.GetDbContext();




回答2:


One tricky way to clone an entity is just serialize and then deserialize the object. Use Newtonsoft for serialization. Simply this code can be used

MyEntity myEntity = _myEntityRepository.get(1);
string cloned = JsonConvert.SerializeObject(myEntity);
MyEntity clonedEntity = JsonConvert.DeserializeObject<MyEntity>(cloned);
clonedEntity.Id = 0;



回答3:


The question is a little ambiguous, but here are a few things for you to consider:

Dependency Injection: AUTOFAC or NINJECT (for example) This will allow you to inject your DbContext into any class via ctor or property to that you can use it.

Pass it as a parameter (how's your service generated?)

var appService = new ApplicationService(new MyDbContext())

Either one of those will work. If that wasn't what you meant, some more info will help :)



来源:https://stackoverflow.com/questions/44986872/asp-net-boilerplate-how-do-i-inject-object-of-dbcontext-in-application-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!