Reputation: 311
I'm trying to implement Autofac in WCF but it is not working .
Step : 1
protected void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
// Register your service implementations.
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<ProjectRepository>().As<IProjectRepository>();
builder.RegisterType<ProjectService>().As<IProjectService>();
builder.RegisterType<DataService>().As<IDataService>();
builder.Register(c => new ProjectRepository(c.Resolve<DatabaseFactory>())).AsSelf();
builder.Register(c => new ProjectService(c.Resolve<ProjectRepository>(),c.Resolve<UnitOfWork>())).AsSelf();
builder.Register(c => new DataService(c.Resolve<ProjectService>())).AsSelf();
//builder.RegisterType<DataService>().As<IDataService>();
// Set the dependency resolver.
var container = builder.Build();
AutofacHostFactory.Container = container;
}
Step : 2
public class DataService : IDataService
{
private IProjectService projectService;
public DataService(IProjectService projectService)
{
this.projectService = projectService;
}
public List<Data.Project> GetProjects()
{
return projectService.GetAllProject();
}
}
On WCF Start it is showing error
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
Blockquote
What I have missed ?
If I implement constructor with 0 parameter then "projectService.GetAllProject(); " projectService object showing null in
public List<Data.Project> GetProjects()
{
return projectService.GetAllProject();
}
Thanks, Pargan
Upvotes: 2
Views: 1745
Reputation: 33379
In order for Autofac to get in the middle of service activation, you need to change to use the AutofacServiceHostFactory. There are different ways of doing this depending on what approach you are using for registering your services.
If you are using .svc files then you need to do the following:
<%@ ServiceHost
Service="MyServices.MyService, MyServices"
Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>
If you are instead using the configuration based approach via <system.serviceModel><serviceHostingEnvironment><serviceActivations>
then would do this instead:
<add service="MyServices.MyService, MyServices" relativeAddress="~/MyService.svc" factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" />
Once you've done that, Autofac will now be in charge of instantiating your service instances and will do so by resolving them from the container you've configured via AutofacHostFactory.Container
.
Upvotes: 1