如何在.net 4.7中获取Iconfiguration和IHostingenvironment?

时间:2018-09-10 14:55:24

标签: c# .net asp.net-mvc

我一直在寻找如何为.net核心执行此操作,但是我正在为netstandard开发一个库,如果我也想在.net 4.7中使用此库,我如何访问iconfiguration和ihosting环境在.net 4.7中。我一直在寻找您需要进行依赖注入才能使其正常工作的信息,但是没有人显示出如何完成此操作的代码示例。

我一直在阅读的所有信息中找到这些代码行,并说一些有关将其注入其中的内容:

    public class Startup
   {
    public void Configuration(IAppBuilder app)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
        DependencyResolver.SetResolver(resolver);
    }
     public void ConfigureServices(IServiceCollection services)
    {   
    }
}

如何获取.net 4.7+中的.net核心iconfiguration / ihostingenvironment等效项?

1 个答案:

答案 0 :(得分:0)

此处的启动代码通常是.NET Core ...对于带有MVC的4.7,您通常使用所需的任何DI框架从Global.asax(DependencyResolver.SetResolver方法)调用Application_Start()( Unity,SimpleInjector,Autofac等)。

这是来自SimpleInjector的建议代码段:

// You'll need to include the following namespaces
using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;

public class WebApiApplication : System.Web.HttpApplication
    // This is the Application_Start event from the Global.asax file.
    protected void Application_Start(object sender, EventArgs e) {

    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();


    // Register your types, for instance:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

发件人:https://simpleinjector.readthedocs.io/en/latest/mvcintegration.html?highlight=mvc

更新

IHostingConfiguration和IConfiguration是仅使用.NET Core实现的接口,在.NET 4.7中不可用。