2017-10-20 170 views
0

Visual Studio - Snapshot of Project StructureAutofac的Web API依賴注入問題

的Global.asax.cs文件,我已經把依賴和註冊的WebAPI控制器

using Autofac; 
using Autofac.Integration.Mvc; 
using Autofac.Integration.WebApi; 
using StructureMap; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 
using GeoLocationApi.Services; 
using GeoLocationApi.Controllers; 
using GeoLocationApi.Models; 
using System.Reflection; 

namespace GeoLocationApi 
{ 
    public class WebApiApplication : System.Web.HttpApplication 
    { 
     protected void Application_Start() 
     { 
      AreaRegistration.RegisterAllAreas(); 
      GlobalConfiguration.Configure(WebApiConfig.Register); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 



      var builder = new ContainerBuilder(); 


      builder.RegisterType<locationService>().InstancePerRequest(); 
      builder.RegisterApiControllers(typeof(locationController).Assembly); 
      builder.RegisterType<locationContext>().As<locationContext>().InstancePerRequest(); 
      builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); 


      var container = builder.Build(); 
      DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 
      GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); 

      builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

     } 
    } 
} 

locationService.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using GeoLocationApi.Models; 
using System.Linq.Expressions; 

namespace GeoLocationApi.Services 
{ 
    public partial class locationService : IlocationService 
    { 
     private readonly IRepository<location> _locationRepository; 

     public locationService(IRepository<location> locationRepository) 
     { 
      this._locationRepository = locationRepository; 
     } 

     public virtual IQueryable<location> GetAllLocations(params Expression<Func<location, object>>[] includeProperties) 
     { 
      return _locationRepository.Table.IncludeProperties(includeProperties); 
     } 
    } 
} 

locationController。 cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using GeoLocationApi.Models; 
using GeoLocationApi.Services; 
using GeoLocationApi.Infrastructure; 

namespace GeoLocationApi.Controllers 
{ 
    [RoutePrefix("api")] 
    public class locationController : ApiController 
    { 
     private readonly IlocationService _locationService; 

     public locationController(IlocationService locationService) 
     { 
      this._locationService = locationService; 
     } 

     [Route("getlocation")] 
     [HttpGet] 
     public locationDTO GetLocationDetails() 
     { 
      var data = _locationService.GetAllLocations().Where(x => x.locationActiveStatus != false); 

      return AutoMapperConfiguration.Mapper.Map<locationDTO>(data); 

     } 
    } 
} 

IRepository.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using GeoLocationApi.Models; 

namespace GeoLocationApi.Services 
{ 
    public partial interface IRepository<T> where T : BaseEntity 
    { 
     /// <summary> 
     /// Get entity by identifier 
     /// </summary> 
     /// <param name="id">Identifier</param> 
     /// <returns>Entity</returns> 
     T GetById(object id); 

     /// <summary> 
     /// Insert entity 
     /// </summary> 
     /// <param name="entity">Entity</param> 
     void Insert(T entity); 

     /// <summary> 
     /// Insert entities 
     /// </summary> 
     /// <param name="entities">Entities</param> 
     void Insert(IEnumerable<T> entities); 

     /// <summary> 
     /// Update entity 
     /// </summary> 
     /// <param name="entity">Entity</param> 
     void Update(T entity); 

     /// <summary> 
     /// Update entities 
     /// </summary> 
     /// <param name="entities">Entities</param> 
     void Update(IEnumerable<T> entities); 

     /// <summary> 
     /// Delete entity 
     /// </summary> 
     /// <param name="entity">Entity</param> 
     void Delete(T entity); 

     /// <summary> 
     /// Delete entities 
     /// </summary> 
     /// <param name="entities">Entities</param> 
     void Delete(IEnumerable<T> entities); 

     /// <summary> 
     /// Gets a table 
     /// </summary> 
     IQueryable<T> Table { get; } 

     /// <summary> 
     /// Gets a table with "no tracking" enabled (EF feature) Use it only when you load record(s) only for read-only operations 
     /// </summary> 
     IQueryable<T> TableNoTracking { get; } 


    } 
} 

locationContext.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data.Entity; 

namespace GeoLocationApi.Models 
{ 
    public class locationContext : DbContext 
    { 
     public DbSet<location> Location { get; set; } 
    } 
} 

location.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace GeoLocationApi.Models 
{ 
    public class location : BaseEntity 
    { 
     public string locationName { get; set; } 
     public string locationDescription { get; set; } 
     public string locationLongitude { get; set; } 
     public string locationLatitutde { get; set; } 
     public bool locationActiveStatus { get; set; } 
    } 
} 

當我運行該項目,我得到在瀏覽器選項卡這是關於錯誤構造器。

<Error> 
<Message>An error has occurred.</Message> 
<ExceptionMessage> 
An error occurred when trying to create a controller of type 'locationController'. Make sure that the controller has a parameterless public constructor. 
</ExceptionMessage> 
<ExceptionType>System.InvalidOperationException</ExceptionType> 
<StackTrace> 
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext() 
</StackTrace> 
<InnerException> 
<Message>An error has occurred.</Message> 
<ExceptionMessage> 
An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = locationController (ReflectionActivator), Services = [GeoLocationApi.Controllers.locationController], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'GeoLocationApi.Controllers.locationController' can be invoked with the available services and parameters: Cannot resolve parameter 'GeoLocationApi.Services.IlocationService locationService' of constructor 'Void .ctor(GeoLocationApi.Services.IlocationService)'. (See inner exception for details.) 
</ExceptionMessage> 
<ExceptionType>Autofac.Core.DependencyResolutionException</ExceptionType> 
<StackTrace> 
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) 
</StackTrace> 
<InnerException> 
<Message>An error has occurred.</Message> 
<ExceptionMessage> 
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'GeoLocationApi.Controllers.locationController' can be invoked with the available services and parameters: Cannot resolve parameter 'GeoLocationApi.Services.IlocationService locationService' of constructor 'Void .ctor(GeoLocationApi.Services.IlocationService)'. 
</ExceptionMessage> 
<ExceptionType>Autofac.Core.DependencyResolutionException</ExceptionType> 
<StackTrace> 
at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable`1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) 
</StackTrace> 
</InnerException> 
</InnerException> 
</Error> 

由於我是新來既#1和ASP.NET Web API,我需要你,請解釋一下我的問題,並告訴我,爲什麼它是未來的錯誤。

在此先感謝和幫助表示讚賞。

+0

當發佈#2的一個問題,總是試圖想出有一個好的頭銜。主要問題應該在標題中。總是關於你的問題的'gooblebility'和一個很好的問題讓別人讀你的問題。 「Autofac Web API依賴注入問題」不是一個好題目。見[this](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。 – Steven

回答

0

我覺得你錯誤地註冊您的locationService,它應該被映射到接口,而不是實際的

builder.RegisterType<locationService>().AsImplementedInterfaces().InstancePerRequest()

+0

感謝您的幫助,但我仍然得到錯誤。 https://s1.postimg.org/1rcxjfajzj/Still-error.png(快照) –

+0

我想這是*新錯誤*,你有沒有註冊你的'庫'? –

+0

你能告訴我我該怎麼做? –