相关疑难解决方法(0)

属性注入失败,使用Autofac

我正在使用Autofac与MVC/Owin和WebApi.

遵循Autofac文档我正在使用设置:

public static void Run(IAppBuilder application) {

  ContainerBuilder builder = new ContainerBuilder();

  HttpConfiguration configuration = GlobalConfiguration.Configuration;

  builder.RegisterControllers(typeof(MvcApplication).Assembly);
  builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
  builder.RegisterModelBinderProvider();
  builder.RegisterModule<AutofacWebTypesModule>();
  builder.RegisterSource(new ViewRegistrationSource());
  builder.RegisterFilterProvider();
  builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
  builder.RegisterWebApiFilterProvider(configuration);

  builder.RegisterType<Test>().As<ITest>().PropertiesAutowired();        

  IContainer container = builder.Build();
  application.UseAutofacMiddleware(container);
  DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

}
Run Code Online (Sandbox Code Playgroud)

然后我在控制器上测试了构造函数和属性注入:

public interface ITest { }
public class Test : ITest { }

public partial class HomeController : Controller {

  private ITest _testConstructor { get; set; }
  public ITest TestProperty { get; set; }

  public HomeController(ITest testConstructor) {

    _testConstructor = testConstructor; …
Run Code Online (Sandbox Code Playgroud)

c# autofac

3
推荐指数
1
解决办法
3956
查看次数

使用Autofac将属性注入自定义WebViewPage

我正在创建一个内部应用程序框架,我们组织中的其他开发团队将使用它来构建MVC应用程序.作为其中的一部分,我正在为所有视图创建菜单结构,从配置中读取并根据当前用户的权限进行修改.要创建菜单作为框架的一部分,我已经创建了WebViewPage一个自定义HTML Helper类的自定义实现,需要依赖于它ApplicationDataReader来构造菜单.

我已经阅读了各种帖子,解释说MVC需要WebViewPage有一个无参数的构造函数,所以我需要使用属性注入.我已经配置了Autofac MVC3集成,包括注册一个ViewRegistrationSource.麻烦的是,当访问依赖属性时,它总是为空.

这是我正在尝试进行的调用的自定义视图页面和帮助程序:

public abstract class OuBaseViewPage<TModel> : WebViewPage<TModel> where TModel : class
{
    public OuHelper<TModel> Ou { get; set; }

    public override void InitHelpers()
    {
        base.InitHelpers();
        Ou = new OuHelper<TModel>(ViewContext, this);
    }
}

public class OuHelper<TModel> where TModel : class
{
    public OuHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)
        : this(viewContext, viewDataContainer, RouteTable.Routes)
    {
    }

    public OuHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)
    {
        ViewContext = viewContext;
        ViewData = new ViewDataDictionary<TModel>(viewDataContainer.ViewData); …
Run Code Online (Sandbox Code Playgroud)

autofac asp.net-mvc-3

2
推荐指数
1
解决办法
2609
查看次数

标签 统计

autofac ×2

asp.net-mvc-3 ×1

c# ×1