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にするとエラーになります。
誰かが正しい方向に私を向けることができますか?
お返事ありがとうございます。私はそれを行ってあげるよ。 – kcis8rm