使用AutoFac解析具有扩展方法的类

InT*_*ons 2 entity-framework autofac graphdiff

我正在使用第三方库GraphDiff,它将扩展方法添加到DBContext类.我的Context类继承自Interface,如下所示

 MyContext: DbContext,IMyContext 
Run Code Online (Sandbox Code Playgroud)

IoC包含注册MyContext作为IMyContext.接口没有扩展方法的签名和第三个.现在我没有得到MyContext将如何使用该扩展方法?如果我创建了MyContext的Object,那么它就有了这个方法,但是当它获得Inject时却没有

Cyr*_*and 6

扩展方法不是类型的一部分,它是C#语法糖.当你这样做时:

myContext.ExtensionMethod(); 
Run Code Online (Sandbox Code Playgroud)

编译器将生成以下代码:

ExtensionContainer.ExtensionMethod(myContext); 
Run Code Online (Sandbox Code Playgroud)

在哪里ExtensionContainer定义如下:

public static class ExtensionContainer 
{
    public static void ExtensionMethod(this DbContext context)
    { }
}
Run Code Online (Sandbox Code Playgroud)

使用扩展方法时,编译器将调用静态方法.有关详细信息,请参阅扩展方法(C#编程指南).

您不能在您的情况下使用扩展方法,因为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
}
Run Code Online (Sandbox Code Playgroud)

在具体的上下文中,您将被允许使用扩展方法

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); 
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是不再依赖IMyContext注射MyContext.此解决方案将使您的应用程序更难以测试,并将引入与Entity Framework的强依赖性.

顺便说一下这样做可能会破坏单一责任原则,但我没有看到一个简单的方法来解决这个问题而没有大的重构.