我一直在寻找如何为.net核心做这个,但我正在研究netstandard的库,如果我想在.net 4.7中使用这个库,那么当我进入时,如何访问iconfiguration和ihosting环境。净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?
这里的启动代码通常是.NET Core ...对于带有MVC的4.7,你通常使用你想要的任何DI框架(Unity,SimpleInjector,Autofac等)从Global.asax(DependencyResolver.SetResolver
方法)调用Application_Start()
。
以下是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
UPDATE
IHostingConfiguration和IConfiguration是仅使用.NET Core实现的接口,在.NET 4.7中不可用。