1

Is it possible to configure Autofac to work with ASP.NET Webforms to use Dependency Injection

my Global Code :

 static IContainerProvider _containerProvider;

    public IContainerProvider ContainerProvider
    {
        get { return _containerProvider; }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<EmployeeManager>().As<IEmployeeManager>().InstancePerRequest();
        _containerProvider = new ContainerProvider(builder.Build());
    }

My Page Code :

 private readonly IEmployeeManager _empManager;
    public WebForm2(IEmployeeManager empManager)
    {
        _empManager = empManager;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        _empManager.GetAllEmployees();
    }

Error : Error

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
salah
  • 41
  • 2
  • 11
  • 1
    There is an entire section of [the docs](http://docs.autofac.org/en/latest/integration/aspnet.html) dedicated to ASP.NET integration, with several sections on dependency injection. – MTCoster Dec 04 '15 at 12:28
  • i edit my post with code i follow all steps still not working (webform.aspx oes not contain a constructor that takes 0 arguments) – salah Dec 04 '15 at 12:53
  • @salah Don't just tell us you followed all steps. List each step you performed in your post and show relevant configuration. A little hint: Web Forms doesn't support constructor injection, just property injection. So you clearly didn't follow all the steps. – mason Dec 04 '15 at 13:53
  • it is worked now but what about inject in asmx file? – salah Dec 04 '15 at 15:27

1 Answers1

2

In order to inject dependencies into web forms pages (System.Web.UI.Page instances) or user controls (System.Web.UI.UserControl instances) you must expose their dependencies as public properties that allow setting. This enables the PropertyInjectionModule to populate those properties for you.
> http://docs.autofac.org/en/latest/integration/webforms.html

Due to internal restriction in ASP.net WebForm, constructor injection in page is not possible. Only property injection is allowed within ASP.net WebForm Pages. The documentation explain how to deal with this restriction.

Cyril Durand
  • 15,834
  • 5
  • 54
  • 62