与Cors的WebApi2的冲突统一DI

时间:2016-03-04 11:02:12

标签: c# asp.net-web-api

我正在使用基于SSO的Oauth2令牌。我的一个应用程序与MachineKey同步到SSO,StartUp配置如下:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        ConfigureOAuth(app);
        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        //Token Consumption
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
        });
    }
}

然后我的Unity DI配置了MVC5和WebAPI2 Take Bellow:

public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        var container = UnityConfig.GetConfiguredContainer();

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    // TODO: Uncomment if you want to use PerRequestLifetimeManager
    // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

DI适用于我的MVC控制器,但对于WebApi控制器不起作用。 感谢。

1 个答案:

答案 0 :(得分:0)

我的问题解决了。

我将webApi配置移动到global.asax的application_start。那么我的startup.cs代码如下:

  def self.exectue
    Organization.has_plan do |o|
      o.channels.each do |c|
        c.users.enabled.send_weekly_report.each do |u|
          u.in_timezone do
            WeeklyReportMailer.delay.send_report(c, u) if Time.zone.now.hour == SEND_HOUR
          end
        end
      end
    end
  end

class Organization
  scope :has_plan, -> { joins(:subscription => :plan)}
end

class User
  scope :enabled, -> { where(disabled: false) }
  scope :send_weekly_report, -> { where(send_weekly_report: true) }
end

class Channel
    belongs_to :organization

    has_many :channel_users
    has_many :users, through: :channel_users
end

我的代码的application_start如下:

public void Configuration(IAppBuilder app)
    {
        //HttpConfiguration config = new HttpConfiguration();
        ConfigureOAuth(app);
        //WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        //app.UseWebApi(config);
    }