11

I'm trying to attempt a structure with Autofac on Wcf.

    namespace WcfService1.Model
    {
        [DataContract(IsReference = true)]
        public partial class Account
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Surname { get; set; }
            [DataMember]
            public string Email { get; set; }
            [DataMember]
            public Nullable<System.DateTime> CreateDate { get; set; }
        }    
    }

Model>IAccounRepository.cs

1.

namespace WcfService1.Model
{
  public interface IAccountRepository
    {
        IEnumerable<Account> GetAllRows();
        bool AddAccount(Account item);
    }
}

Model>AccounRepository.cs

2.

namespace WcfService1.Model
{
    public class AccountRepository:IAccountRepository
    {
        private Database1Entities _context;
        public AccountRepository()
        {
            if(_context == null)
                _context =new Database1Entities();
        }

        public IEnumerable<Account> GetAllRows()
        {
            if (_context == null)
                _context = new Database1Entities();
            return _context.Account.AsEnumerable();
        }        

        public bool AddAccount(Account item)
        {
            try
            {
                if (_context == null)
                    _context = new Database1Entities();
                _context.Entry(item).State = EntityState.Added;
                _context.Account.Add(item);
                _context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                var str = ex.Message;
                return false;
            }
        }
    }
}
  1. DbConnection > EntityFramework + DbContext

  2. IService1.cs

Code:

namespace WcfService1
{
    [ServiceContract(SessionMode = SessionMode.Allowed)]
    public interface IService1
    {
        [OperationContract]
        IList<Account> GetAccounts();

        [OperationContract]
        bool AddAccount(Account item);
    }
}
  1. Service1.cs

Code:

namespace WcfService1
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1:IService1
    {
        private readonly IAccountRepository _repository;
        public Service1(IAccountRepository repository)
        {
            _repository = repository;
        }    
        public IList<Account> GetAccounts()
        {   
            var items = _repository.GetAllRows().ToList();
            return items;
        }
        public bool AddAccount(Account item)
        {
            item.CreateDate = DateTime.Now;    
            return _repository.AddAccount(item);
        }
    }
}
  1. Service1.svc

Code:

<%@ ServiceHost Language="C#"
                Debug="true"
                Service="WcfService1.Service1, WcfService1"
                Factory="Autofac.Integration.Wcf.AutofacWebServiceHostFactory, Autofac.Integration.Wcf" %>
  1. Global.asax.cs

Code:

protected void Application_Start(object sender, EventArgs e)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType< AccountRepository>().As< IAccountRepository>();
            builder.RegisterType< Service1 >().As< IService1>();

            AutofacHostFactory.Container = builder.Build();
        }

I'm getting the following error, could not find a solution. What's my wrong.

Error Message :

Server Error in '/' Application.

The service 'WcfService1.Service1, WcfService1' configured for WCF is not registered with the Autofac container. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The service 'WcfService1.Service1, WcfService1' configured for WCF is not registered with the Autofac container.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: The service 'WcfService1.Service1, WcfService1' configured for WCF is not registered with the Autofac container.]
   Autofac.Integration.Wcf.AutofacHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +667
   System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +2943
   System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +88
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1239

[ServiceActivationException: The service '/Service1.svc' cannot be activated due to an exception during compilation.  The exception message is: The service 'WcfService1.Service1, WcfService1' configured for WCF is not registered with the Autofac container..]
   System.Runtime.AsyncResult.End(IAsyncResult result) +454
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +413
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, String routeServiceVirtualPath, Boolean flowContext, Boolean ensureWFService) +327
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext, Boolean ensureWFService) +46
   System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +384
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +238
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +114
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Eray Çakır
  • 111
  • 1
  • 3

7 Answers7

20

In addition to the other answers, you should make sure you're using the fully-qualified service name in the Service attribute of the ServiceHost element in your .svc file.

For example, instead of:

<%@ ServiceHost Language="C#" Debug="true" Service="MoviesService.MoviesService" CodeBehind="MoviesService.svc.cs" %>

Use:

<%@ ServiceHost Language="C#" Debug="true" Service="MoviesService.MoviesService, MoviesService" CodeBehind="MoviesService.svc.cs" %>

Source: http://jmonkee.net/wordpress/2011/09/05/autofac-wcfintegration-service-not-registered-with-the-autofac-container/

Jonathan
  • 32,202
  • 38
  • 137
  • 208
  • 2
    This saved me a lot of frustration. I had thought I'd been following the guidelines to the letter. At the risk of breaching SO guidelines, many thanks. – Rob Lyndon Nov 18 '13 at 13:59
  • Really helpful, I spent 30 minutes wondering why my service doesn't work – stann1 Aug 05 '15 at 14:17
  • At first I disregarded this as I assumed it's on by default, but what do you know... it's not... good thing I stumbled onto this. thx – veljkoz Jul 06 '17 at 15:34
4

You should register the service as self, not as the interface.

builder.RegisterType< Service1 >().AsSelf();
jgauffin
  • 99,844
  • 45
  • 235
  • 372
2

Just Register the Service1 Like this builder.RegisterType<Service1>(); instead builder.RegisterType<Service1>().As<IService1>();

Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
2

You should write in .svc file (Namespace1):

<%@ ServiceHost Language="C#" Debug="true" Service="Namespace1.Service1, Namespace1"
   Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" CodeBehind="Service1.svc.cs" %>
David Buck
  • 3,752
  • 35
  • 31
  • 35
0

Give this a try:

var builder = new ContainerBuilder();

builder.Register(c => new AccountRepository()).As<IAccountRepository>();
builder.Register(c => new Service1(c.Resolve<IAccountRepository>())).AsSelf();

AutofacHostFactory.Container = builder.Build();
peteski
  • 1,455
  • 3
  • 18
  • 40
0

You should not use. `builder.RegisterType< Service1 >().As' but use RegisterType without extension methods 'builder.RegisterType();'

CrIceIs
  • 347
  • 3
  • 6
0

For me I was using a Project called 'WCF Service'

This by default gave me a name space called WCF_Service, and a assembly name of 'WCF Service'

None of the fixes worked until that space was removed.

Jon H
  • 1,061
  • 4
  • 13
  • 32