如何在ashx中使用依赖注入(Autofac,MVC4)

时间:2013-05-13 09:01:12

标签: asp.net-mvc dependency-injection autofac

public class AutoCompleteCity : IHttpHandler
{
    public IAutoCompleteRepository AutoCompleteRepository { get; set; }

    public void ProcessRequest(HttpContext context)
    {
    }
}

public static void RegisterDependencies()
{
    var builder = new ContainerBuilder();

    builder.RegisterType<AutoCompleteRepository>().As<IAutoCompleteRepository>).SingleInstance();
    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

AutoCompleteRepository已在SingleInstance中注册,但在调用ProcessRequest时始终为null。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您的代码看起来不错。我怀疑你在web.config中的PropertyInjectionModule httpModules设置中缺少了。 Autofac需要以下模块设置才能与ASP.Net良好协作:

  <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
  <add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>

注意:ASP.Net WebForms集成的设置描述为here

答案 1 :(得分:1)

尝试在构造函数中注入依赖项,如果要进行属性注入,则应使用以下命令启用它:PropertiesAutowired(),一般使用autofac,如果要使用属性注入,则需要使用PropertiesAutowired()配置为类启用它你想要获得注入属性,而不是你要注入的类。

首选方式:

public class AutoCompleteCity : IHttpHandler
{
    public IAutoCompleteRepository AutoCompleteRepository { get; set; }
    public AutoCompleteCity(IAutoCompleteRepository autoCompleteRepository) {
        AutoCompleteRepository = autoCompleteRepository;
    }

    public void ProcessRequest(HttpContext context)
    {
    }

}

或试试这个:

public static void RegisterDependencies()
{
    var builder = new ContainerBuilder();

    builder.RegisterType<AutoCompleteRepository>().As<IAutoCompleteRepository>()
           .SingleInstance();

    builder.RegisterType<AutoCompleteCity>()
      .As<IHttpHandler>()
      .PropertiesAutowired(); //<--!!!

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

编辑: 看这里:https://groups.google.com/forum/#!topic/autofac/BkY4s4tusUc,学习如何注册IHttpHandler。

答案 2 :(得分:0)

你可以试试这个

public class AutoCompleteCity : IHttpHandler
{

 private IAutoCompleteRepository _repo;


public IAutoCompleteRepository Repository
{
   get
   {
       if (_repo==null)
       {
            _repo=AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<IAutoCompleteRepository>();           
        }
       return _repo;
   }
   set
   {
     if (value!=null) _repo=value;
   }
 }
 public void ProcessRequest(HttpContext context)
 {
 }
 }