2017-10-03 2 views
0

MVC에서 autofac을 사용하는 방법을 배워서 많은 행운을 얻지 못했습니다.MVC 5에서 autofac

[Authorize] 
public class NotificationsController : ApiController 
{ 
    private ApplicationDbContext _context; 
    private readonly IMapper _mapper; 

    public NotificationsController(IMapper notificationMapper) 
    { 
     _context = new ApplicationDbContext(); 
     _mapper = notificationMapper; 
    } 

    public IEnumerable<NotificationDto>GetNewNotifications() 
    { 
     var userId = User.Identity.GetUserId(); 

     var notifications = _context.UserNotifications 
          .Where(un => un.UserId==userId) 
          .Select(un=>un.Notification) 
          .Include(n=>n.Gig.Artist).ToList(); 




     return notifications.Select(notification => _mapper.Map<NotificationDto>(notification)).ToList(); 


    } 
} 

내 Global.asax에 있습니다 : :

나는 4.01 및 Autofac의 v4.6.1

나는 다음과 같은 컨트롤러가 한 Nuget 버전에서 Autofac.mvc5를 설치

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



    } 

    private void ConfigureAutofac() 
    { 
     var autoMapperConfig = new MapperConfiguration(c => 
     { 
      c.AddProfile(new NotificationProfile()); 
     }); 

     var mapper = autoMapperConfig.CreateMapper(); 

     var builder = new ContainerBuilder(); 
     builder.RegisterInstance(mapper); 

     builder.Register(x => new NotificationsController(x.Resolve<IMapper>())); 

     var container = builder.Build(); 
     DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 
    } 
} 

무엇 내가 찾는 것은 우편함을 사용하여 이것을 호출 할 때 매개 변수없는 구성자를 필요로한다는 오류가 발생하지만 _mapper가 null 인 생성자를 넣으면 오류가 발생합니다.

나를 올바른 방향으로 안내해 줄 수 있습니까?

답변

1

컨트롤러가 ApiController에서 파생되었으므로 MVC를 사용하지 않고 WebApi (WebApi2 가정)를 사용하고 있습니다. 따라서 Controller과 MVC를 사용하거나 WebApi2를 처리하기 위해 Autofac.WebApi2 NuGet 패키지를 설치해야합니다.

또한 모든 컨트롤러를 수동으로 등록하는 대신 MVC에 RegisterControllers()을 사용하거나 WebApi에 RegisterApiControllers()을 사용하여 모든 컨트롤러를 한 번에 등록 할 수 있습니다. 특히, NotificationController에 멋진 장식을 사용하지 않고 더 많은 사용자 정의 등록이 필요한 경우.

설명서에 잘 설명되어 있으며 MVC 또는 WebApi으로 Autofac을 사용하는 방법부터 시작해야합니다.

+0

응답 해 주셔서 감사합니다. 나는 그것을 줄 것이다. – kcis8rm

관련 문제