将结构图与MVC和Webapi一起使用

时间:2018-06-22 13:05:57

标签: c# asp.net-mvc asp.net-web-api inversion-of-control structuremap

我在应用程序和structuremap中同时使用MVC和Web api来实现IoC。 当我使用MVC控制器中的任何一个时,IoC都可以正常工作,并且没有出现任何错误,但是在使用Web api控制器后,例如,将某些内容发布到服务器上的 IoCControllerFactory GetControllerInstance 方法中strong>会覆盖默认的控制器工厂,并抛出无效的操作异常。我认为它创建的是MVC控制器的实例,而不是Web api控制器。

这是我的代码:

IoCFactory.cs

public class IoCFactory
{
   private static readonly Lazy<Container> _containerBuilder =
       new Lazy<Container>(defaultContainer,LazyThreadSafetyMode.ExecutionAndPublication);

public static IContainer Container
{
    get { return _containerBuilder.Value; }
}

private static Container defaultContainer()
{
    var container = new Container(x =>
     {
         x.For<IContextProvider>().LifecycleIs<TransientLifecycle>().Use<ContextProvider>();
         x.For<IAccountService>().LifecycleIs<TransientLifecycle>().Use<AccountService>();
         x.For<IActivityService>().LifecycleIs<TransientLifecycle>().Use<ActivityService>();
         x.For<IProjectService>().LifecycleIs<TransientLifecycle>().Use<ProjectService>();
         x.For<ILogService>().LifecycleIs<TransientLifecycle>().Use<LogService>();
         //x.For<IFilterProvider>().Use<StructureMapFilterProvider>();
     });

    container.AssertConfigurationIsValid();
    return container;
    }}

IoCControllerFactory.cs

public class IoCControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContextrequestContext, Type controllerType)
{
    if (controllerType == null)
        throw new InvalidOperationException(string.Format("Page not found: {0}", requestContext.HttpContext.Request.RawUrl));
    return IoCFactory.Container.GetInstance(controllerType) as Controller;
}}

IoCWebApiControllerFactory.cs

public class IoCWebApiControllerFactory : IHttpControllerActivator
{
    private readonly IContainer _container;

    public IoCWebApiControllerFactory(IContainer container)
    {
        _container = container;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        var nestedContainer = _container.GetNestedContainer();
        request.RegisterForDispose(nestedContainer);
        return (IHttpController)nestedContainer.GetInstance(controllerType);
    }}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        var container = IoCFactory.Container;

        GlobalConfiguration.Configuration.Services.Replace(
            typeof(IHttpControllerActivator), new IoCWebApiControllerFactory(container));

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ControllerActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );

        config.Routes.MapHttpRoute(
            name: "ControllerApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );}}

我还将这段代码添加到 Application_Start

ControllerBuilder.Current.SetControllerFactory(new IoCControllerFactory());

此代码有什么问题,我该怎么办?

谢谢

0 个答案:

没有答案