autofac wcf注册错误

时间:2012-08-27 13:42:29

标签: wcf autofac

我正在尝试在Wcf上尝试使用Autofac的结构。

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

模型&GT; IAccounRepository.cs

1

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

模型&GT; 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&gt; EntityFramework + DbContext

  2. IService1.cs

  3. 代码:

    namespace WcfService1
    {
        [ServiceContract(SessionMode = SessionMode.Allowed)]
        public interface IService1
        {
            [OperationContract]
            IList<Account> GetAccounts();
    
            [OperationContract]
            bool AddAccount(Account item);
        }
    }
    
    1. Service1.cs
    2. 代码:

      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
      2. 代码:

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

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

          我收到以下错误,无法找到解决方案。我错了。

          错误讯息:

          '/'应用程序中的服务器错误。

          为WCF配置的服务'WcfService1.Service1,WcfService1'未向Autofac容器注册。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

          异常详细信息:System.InvalidOperationException:为WCF配置的服务“WcfService1.Service1,WcfService1”未向Autofac容器注册。

          来源错误:

          在执行当前Web请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息。

          堆栈追踪:

          [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
          

7 个答案:

答案 0 :(得分:17)

除了其他答案之外,您还应确保在.svc文件中的ServiceHost元素的Service属性中使用完全限定的服务名称。

例如,而不是:

<%@ 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/

答案 1 :(得分:4)

您应该将服务注册为self,而不是接口。

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

答案 2 :(得分:2)

只需注册Service1,就像builder.RegisterType<Service1>(); builder.RegisterType<Service1>().As<IService1>();

一样

答案 3 :(得分:0)

尝试一下:

var builder = new ContainerBuilder();

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

AutofacHostFactory.Container = builder.Build();

答案 4 :(得分:0)

你不应该使用。   `builder.RegisterType&LT; Service1&gt;()。作为' 但是使用RegisterType而不使用扩展方法   'builder.RegisterType();'

答案 5 :(得分:0)

对我而言,我使用的是名为“WCF服务”的项目

默认情况下,这给了我一个名为WCF_Service的名称空间,以及一个名为&#39; WCF Service&#39;

的程序集名称

在删除该空格之前,没有任何修复工作。

答案 6 :(得分:0)

您应该在.svc文件(Namespace1)中写入:

<%@ ServiceHost Language="C#" Debug="true" Service="Namespace1.Service1, Namespace1"
   Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" CodeBehind="Service1.svc.cs" %>