Hi Alexey,
I'm going to respond to your email here for the benefit of others.
Hello, Alex.
I am trying figured out is there a way to implement DI with Autofac into Web Service?
Based on my investigation, we can made a DI into property, but unfortunately into constructor we can't due to No parameterless constructor defined for this object. Because WebService required default constructor! But I found that another DI frameworks for example Spring.Net supports injections into constructor! You can find such sample by http://www.gitshah.com/2011/11/integrating-springnet-with-asmx.html. SO my question is why Autofac does't support similar thing to do?
Thank's for you answer!
The SoapHttpClientProtocol based proxies have never supported DI natively. Making this work is really not worth the effort for us given how little interest there is in ASMX web services.
To make it work Spring.NET had to implement a dynamic proxy, custom HTTP handler, and custom configuration of the web service.
A simpler approach would be to use service location in the web service and have it call directly through to the real implementation. Service location is generally an anti-pattern but can be acceptable in situations such as these when the use is kept to a minimum. Essentially the web service would be a small shim that delegates all work to the service implementation resolved from the container.
There is an Autofac implementation of CommonServiceLocator that you could use to access the container.
The end result would look something like this.
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
var service = ServiceLocator.Current.GetInstance<IMyBusinessService>();
return service.HelloWorld();
}
}
public class MyBusinessService : IMyBusinessService
{
readonly IDependency dependency;
public MyBusinessService(IDependency dependency)
{
this.dependency = dependency;
}
public string HelloWorld()
{
return dependency.SayHello();
}
}
If you want anything more than that you are going to be in for a lot work.
Cheers,
Alex.