我正在尝试将IApplicationConfigurationSection
实现注入这个 MVC5 Controller
,这样我就可以在我web.config
的所有视图中从我的自定义部分访问一些信息(各种字符串):
public class BaseController : Controller
{
public IApplicationConfigurationSection AppConfig { get; set; }
public BaseController()
{
ViewBag.AppConfig = AppConfig; // AppConfig is always null
}
}
我想使用 setter 注入,这样我就不必将派生的Controller
构造函数与他们并不真正关心的参数混在一起。
注意:如果有更好的方法来注入基类依赖项,请告诉我。我承认我在这里可能没有走上正轨。
在我Global.asax
加载我的 StructureMap 配置:
private static IContainer _container;
protected void Application_Start()
{
_container = new Container();
StructureMapConfig.Configure(_container, () => Container ?? _container);
// redacted other registrations
}
我的StructureMapConfig
班级加载我的注册表:
public class StructureMapConfig
{
public static void Configure(IContainer container, Func<IContainer> func)
{
DependencyResolver.SetResolver(new StructureMapDependencyResolver(func));
container.Configure(cfg =>
{
cfg.AddRegistries(new Registry[]
{
new MvcRegistry(),
// other registries redacted
});
});
}
}
我的 MvcRegistry 提供了 StructureMap 的映射:
public class MvcRegistry : Registry
{
public MvcRegistry()
{
For<BundleCollection>().Use(BundleTable.Bundles);
For<RouteCollection>().Use(RouteTable.Routes);
For<IPrincipal>().Use(() => HttpContext.Current.User);
For<IIdentity>().Use(() => HttpContext.Current.User.Identity);
For<ICurrentUser>().Use<CurrentUser>();
For<HttpSessionStateBase>()
.Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session));
For<HttpContextBase>()
.Use(() => new HttpContextWrapper(HttpContext.Current));
For<HttpServerUtilityBase>()
.Use(() => new HttpServerUtilityWrapper(HttpContext.Current.Server));
For<IApplicationConfigurationSection>()
.Use(GetConfig());
Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());
}
private IApplicationConfigurationSection GetConfig()
{
var config = ConfigurationManager.GetSection("application") as ApplicationConfigurationSection;
return config; // this always returns a valid instance
}
}
我也“举起手来”并尝试使用[SetterProperty]
BaseController 上的属性 - 该技术也失败了。
尽管我尽最大努力寻找解决方案,但AppConfig
我的控制器构造函数中的属性始终是null
. 我以为
`Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());`
会做的伎俩,但它没有。
我发现如果我放弃 setter 注入并使用构造函数注入,它会像宣传的那样工作。我仍然想知道我哪里出错了,但我想强调我不是 StructureMap 大师 -可能有更好的方法来避免构造函数注入我的基类依赖项。如果你知道我应该怎么做,但不是,请分享。