簡體   English   中英

“沒有為此對象定義無參數的構造函數。”對於使用結構映射的控制器中的IBus

[英]“No parameterless constructor defined for this object.” for IBus in controller using StructureMap

我正在嘗試使用NServiceBus設置StructureMap。 我已經下載了所有軟件包,並且NuGet為我創建了一些文件:

NuGet為StructureMap創建的新文件

這是這些文件中的代碼

IoC.cs:

public static class IoC {
    public static IContainer Initialize() {
        var cont = new Container();
        cont.Configure(x =>
                    {
                        x.Scan(scan =>
                                {
                                    scan.TheCallingAssembly();
                                    scan.WithDefaultConventions();
                                });
                        //x.For<IExample>().Use<Example>();
                    });
        return cont;
    }
}

StructureMap.cs:

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyProjectName.App_Start.StructuremapMvc), "Start")]

namespace MyProjectName.App_Start {
    public static class StructuremapMvc {
        public static void Start() {
            IContainer container = IoC.Initialize();
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
        }
    }
}

沒有更改任何內容,因此創建了這些文件。 然后,我在其中一個控制器中添加了一個構造函數:

public class ProductsController : Controller
{
    private readonly IBus _bus;

    public ProductsController(IBus bus)
    {
        _bus = bus;
    }

    public ActionResult Index()
    {
        ViewBag.Title = "Product list";

        var message = new ProductMessage();
        _bus.Send(message);

        return View();
    }
}

那是我得到錯誤的時間

沒有為此對象定義無參數構造函數。

這很奇怪,因為這條線

scan.WithDefaultConventions();

如果我要注入IBus,則應排除此問題。

我已經嘗試了什么:

  • 從StructuremapMvc.cs中刪除[assembly:...],然后從Global.asax中調用StructuremapMvc.Start()。 結果相同。
  • 在控制器中添加了無參數構造函數,其主體如下:

    _bus = _bus = new Container()。GetInstance <IBus>();

    但是_bus仍然為空,並且我有一個與此相關的異常。

請協助。

您應為自己的代碼和NServiceBus配置相同的容器。 下面的代碼顯示了StructureMap的此配置。

BusConfiguration busConfiguration = new BusConfiguration();

//Configure the container and use the same one for MVC and NServiceBus    
Container container = new Container();

busConfiguration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container));

更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM