2017-10-03 10 views
0

MVCでautofacを使用する方法を学びたいと思っています。MVCのオートファンクション5

私は、次のコントローラを持っているNugetバージョン4.01 とAutofacのv4.6.1

からAutofac.mvc5をインストール:

[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のは、次のとおりです。

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