Подтвердить что ты не робот

Ошибка регистрации autocac wcf

Я пытаюсь создать структуру с Autofac на 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; }
        }    
    }

Модель > IAccounRepository.cs

1.

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

Модель > 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;
            }
        }
    }
}
  • DbConnection > EntityFramework + DbContext

  • IService1.cs

Код:

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

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

код:

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);
        }
    }
}
  • Service1.svc

код:

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

Код:

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();
        }

Я получаю следующую ошибку, не могу найти решение. Какая моя ошибка.

Сообщение об ошибке:

Ошибка сервера в приложении "/".

Служба WcfService1.Service1, WcfService1, настроенная для WCF, не регистрируется в контейнере Autofac. Описание: Необработанное исключение возникло во время выполнения текущего веб-запроса. Просмотрите трассировку стека для получения дополнительной информации об ошибке и ее возникновении в коде.

Сведения об исключении: System.InvalidOperationException: служба WcfService1.Service1, WcfService1, настроенная для WCF, не зарегистрирована в контейнере Autofac.

Ошибка источника:

Необработанное исключение было создано во время выполнения текущего веб-запроса. Информация о происхождении и местоположении исключения может быть идентифицирована с использованием трассы стека исключений ниже.

Трассировка стека:

[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
4b9b3361

Ответ 1

В дополнение к другим ответам вы должны убедиться, что используете полнофункциональное имя службы в атрибуте Service элемента ServiceHost в вашем файле .svc.

Например, вместо:

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

Использование:

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

Источник: http://jmonkee.net/wordpress/2011/09/05/autofac-wcfintegration-service-not-registered-with-the-autofac-container/

Ответ 2

Вы должны зарегистрировать службу как самостоятельно, а не как интерфейс.

builder.RegisterType< Service1 >().AsSelf();

Ответ 3

Просто зарегистрируйте Service1 Как этот builder.RegisterType<Service1>(); вместо builder.RegisterType<Service1>().As<IService1>();

Ответ 4

Попробуйте:

var builder = new ContainerBuilder();

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

AutofacHostFactory.Container = builder.Build();

Ответ 5

Вы не должны использовать. `Builder.RegisterType < Service1 > () но использовать RegisterType без методов расширения 'Builder.RegisterType();'

Ответ 6

Для меня я использовал проект под названием "Служба WCF"

Это по умолчанию дало мне пространство имен, называемое WCF_Service, и имя сборки 'WCF Service'

Ни один из исправлений не работал, пока это место не было удалено.