我正在使用AspNet Core 1.0 RTM的结构图.它们似乎已使用属性上的FromServices属性删除.这打破了下面的代码,因为我现在无法注入ClaimsPrincipal.我不知道如何让DI系统获得这个属性.我是否需要创建自定义InputFormatter或其他内容.重新开始工作似乎需要付出很多努力.
Startup.cs
public class Startup {
public IServiceProvider ConfigureServices(IServiceCollection services) {
var container = new Container();
container.Configure(i => {
i.For<IHttpContextAccessor>()
.Use(new HttpContextAccessor());
i.For<ClaimsPrincipal>()
.Use(x => x.GetInstance<IHttpContextAccessor>().HttpContext.User);
});
container.Populate(services);
return container.GetInstance<IServiceProvider>();
}
}
Run Code Online (Sandbox Code Playgroud)
Model.cs
public class Model {
//[FromServices] <-- worked in RC1
public ClaimsPrincipal Principal { get; set; }
public string Value => Principal.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)
TestController.cs
public class TestController : Controller {
public IActionResult Test(Model model){
return Ok();
}
}
Run Code Online (Sandbox Code Playgroud) 好的,我收到堆栈错误。它被捕获的文件在这里
using System.Web;
using NHibernate;
using Nichols.Web.App_Start;
namespace Nichols.Web.DependencyResolution
{
public class StructureMapScopeModule : IHttpModule
{
public void Dispose()
{
StructuremapMvc.StructureMapDependencyScope.Dispose();
}
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, e) =>
{
InitializeNestedContainerForRequest();
var session = GetCurrentSession();
session.BeginTransaction();
};
context.EndRequest += (sender, e) =>
{
var session = GetCurrentSession();
if (context.Context.Error == null
&& IsOk(context.Response.StatusCode))
{
session.Transaction.Commit();
}
else
{
session.Transaction.Rollback();
}
DisposeNestedContainerForRequest();
};
}
private ISession GetCurrentSession()
{
var container = StructuremapMvc.StructureMapDependencyScope.CurrentNestedContainer;
return container.GetInstance<ISession>();
}
private void InitializeNestedContainerForRequest() …Run Code Online (Sandbox Code Playgroud) 我正在使用 StructureMap 来解决依赖关系,这在旧版本中运行良好。但是在更新 StructureMap 版本 4.2.0.40 后,我遇到了这个错误。
ObjectFactory 现在在新版本中已过时。 那么如何修改以下逻辑以适应更新版本。
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if ((requestContext == null) || (controllerType == null))
return null;
return (Controller)ObjectFactory.GetInstance(controllerType);
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw new Exception(ObjectFactory.WhatDoIHave());
}
}
Run Code Online (Sandbox Code Playgroud)
引导程序
public static class Bootstrapper
{
public static void Run()
{
ControllerBuilder.Current
.SetControllerFactory(new StructureMapControllerFactory());
ObjectFactory.Initialize(x =>
{
x.AddConfigurationFromXmlFile(@"D:\Samples\Web_API\OneCode\StructureMap.Web\StructureMap.Web\StructureMap.xml");
});
}
}
}
Run Code Online (Sandbox Code Playgroud) structuremap asp.net-mvc asp.net-mvc-4 structuremap3 structuremap4