问题
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