扩展方法不是类型的一部分,它是一个 C# syntactic sugar。当你这样做时:
myContext.ExtensionMethod();
编译器将生成以下代码:
ExtensionContainer.ExtensionMethod(myContext);
ExtensionContainer 的定义如下:
public static class ExtensionContainer
{
public static void ExtensionMethod(this DbContext context)
{ }
}
当您使用扩展方法时,编译器将调用静态方法。有关更多信息,请参阅Extension Methods (C# Programming Guide)。
您不能在您的情况下使用扩展方法,因为context 不再是DbContext,而是IMyContext,并且扩展方法是为DbContext 而不是为IMyContext 定义的。
如果您想使用这些扩展方法,一种可能的解决方案是将它们添加到您的界面中。
public interface IMyContext
{
T UpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping, UpdateParams updateParams = null) where T : class
// other methods / properties
}
并且在您的具体上下文中,您将被允许使用扩展方法
public class MyContext : DbContext, IMyContext
{
public T UpdateGraph<T>(T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping, UpdateParams updateParams = null) where T : class
{
DbContextExtensions.UpdateGraph<T>(this, entity, mapping, updateParams);
}
}
另一个解决方案是不再依赖IMyContext,而是注入MyContext。此解决方案将使您的应用程序更难测试,并将引入与 Entity Framework 的强依赖关系。
顺便说一句,这样做可能会破坏Single Responsibility Principle,但我没有看到一个简单的方法来解决这个问题而无需大的重构。