I have a housekeeping services that I am dynamically injecting when saving an entity in my DbContext.
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
var t = entityEntry.Entity.GetType();
// Housekeep
var castEntityEntry = castDbEntityEntryMethod
.MakeGenericMethod(new[] { t })
.Invoke(entityEntry, null);
housekeepEntityMethod
.MakeGenericMethod(new[] { t })
.Invoke(this, new[] { castEntityEntry });
return base.ValidateEntity(entityEntry, items);
}
private void HousekeepEntity<TEntity>(DbEntityEntry<TEntity> entity)
where TEntity : class
{
var housekeeper = DbConfiguration.DependencyResolver.GetService<IHousekeeper<TEntity>>();
if (housekeeper != null)
{
housekeeper.Maintain(entity);
}
}
I had been passing IComponentContext
around everywhere so I could Resolve the type there, but with EF6 I hoped to use the dependency injection:
private class AutofacDbDependencyResolver : AutofacWebApiDependencyResolver, IDbDependencyResolver
{
public AutofacDbDependencyResolver(ILifetimeScope container)
: base(container)
{
}
public object GetService(System.Type type, object key)
{
using (var scope = this.GetRequestLifetimeScope())
{
if (scope == null)
{
return null;
}
object service;
scope.TryResolve(type, out service);
return service;
}
}
public System.Collections.Generic.IEnumerable<object> GetServices(System.Type type, object key)
{
using (var scope = this.GetRequestLifetimeScope())
{
if (scope == null)
{
return System.Linq.Enumerable.Empty<object>();
}
object service;
if (scope.TryResolve(type, out service))
{
return new object[] { service };
}
else
{
return System.Linq.Enumerable.Empty<object>();
}
}
}
}
When setting up container:
System.Data.Entity.DbConfiguration.Loaded += (s, e) =>
e.AddDependencyResolver(new AutofacDbDependencyResolver(container), overrideConfigFile: false);
However my lifetime scopes return null. How can I get the current API request which calls this action?