定义Ninject的绑定,不保留代码DRY的范围

问题描述 投票:0回答:1

我在解决方案中有一个Web项目和一个Windows Service项目。我为这2个项目创建了2个不同的绑定模块,但是您可以看到它有很多重复的代码...唯一的区别是,我在Web项目中使用InRequestScope(),在InTransientScope()中使用用于Windows服务项目。

是否可以合并绑定,并根据项目/入口点添加范围?

public class WebModule : NinjectModule
{
    public override void Load()
    {
        Bind<ApplicationDbContext>().ToSelf().InRequestScope();
        Bind<IMyRepository>().To<MyRepository>().InRequestScope();
        // more types ... InRequetScope();
    }
}

public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<ApplicationDbContext>().ToSelf().InTransientScope();
        Bind<IMyRepository>().To<MyRepository>().InTransientScope();
        // more types ... InTransientScope();
    }
}
c# dependency-injection ninject
1个回答
1
投票

我想出的最佳解决方案是创建一个扩展方法:

public static class NinjectExtensions
{
    public static IBindingNamedWithOrOnSyntax<T> GetScopeByName<T>(this IBindingInSyntax<T> syntax, string scope)
    {
        if (scope.Equals("request", StringComparison.InvariantCultureIgnoreCase))
        {
            return syntax.InRequestScope();
        }
        else if (scope.Equals("thread", StringComparison.InvariantCultureIgnoreCase))
        {
            return syntax.InThreadScope();
        }
        else if (scope.Equals("singleton", StringComparison.InvariantCultureIgnoreCase))
        {
            return syntax.InSingletonScope();
        }

        return syntax.InTransientScope();
    }
}

并动态设置范围。

public class MyModule : NinjectModule
{
    private string _scope = "transient";

    public MyModule()
    {
        if (Convert.ToBoolean(ConfigurationManager.AppSettings["IsWebProject"]))
        {
            _scope = "request";
        }
    }

    public override void Load()
    {
        Bind<ApplicationDbContext>().ToSelf().GetScopeByName(_scope);
        Bind<IMyRepository>().To<MyRepository>().GetScopeByName(_scope);
        // more types ... InRequetScope();
    }
}

注意:我不确定是否有更好的解决方案...这只是我想到的最干净的方法。

© www.soinside.com 2019 - 2024. All rights reserved.