Configure Startup.Cs in Asp.Net Core

Asked

Viewed 370 times

0

Hello, I am unable to configure my Startup.Cs to run my application in . Net Core. The following error is being executed:

An error occurred while Starting the application. Invalidoperationexception: No service for type 'Owin.Iappbuilder' has been Registered. Microsoft.Extensions.Dependencyinjection.ServiceProviderServiceExtensions.Getrequiredservice(Iserviceprovider Provider, Type serviceType)

Exception: Could not resolve a service of type 'Owin.Iappbuilder' for the Parameter 'app' of method 'Configure' on type 'PROJETO.WebAPI.Startup'. Microsoft.AspNetCore.Hosting.Internal.Configurebuilder.Invoke(Object instance, Iapplicationbuilder Builder)

Invalidoperationexception: No service for type 'Owin.Iappbuilder' has been Registered.

Below the code of my class Startup.Cs, I appreciate any help!

[assembly: OwinStartup("BANCO_DADOS", typeof(Startup))]
namespace PROJETO_APP.WebAPI
{
public class Startup
{
    //public Startup(IConfiguration configuration)
    //{
    //    Configuration = configuration;
    //}



    //public IConfiguration Configuration { get; }

    public void Configure(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        var container = new UnityContainer();

        ConfigureDependencyInjection(config, container);

        ConfigureWebApi(config);

        // configuracao de autencticacao
        ConfigureOAuth(app, container.Resolve<IProfissionalApplication>(), container.Resolve<ISistemaContextoApplication>());

        app.UseStageMarker(PipelineStage.MapHandler);

        app.UseCors(CorsOptions.AllowAll);

        app.UseWebApi(config);
    }

    public void ConfigureWebApi(HttpConfiguration config)
    {
        // configuracoes pertinentes aos JSONs
        var formatters = config.Formatters;
        formatters.Remove(formatters.XmlFormatter);

        var jsonSettings = formatters.JsonFormatter.SerializerSettings;
        jsonSettings.Formatting = Formatting.Indented;

        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        formatters.JsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
        formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
        formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}",
            new { id = RouteParameter.Optional });
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddCors();
        services.AddSingleton<IUnitOfWork, UnitOfWork>();


        #region Injeção de dependências de applications

        services.AddSingleton<IAreaApplication, AreaApplication>();
        services.AddSingleton<IAtividadeApplication, AtividadeApplication>();

        #endregion

        #region Injeção de dependências de repositories

        services.AddSingleton<IAreaRepository, AreaRepository>();
        services.AddSingleton<IAtividadeRepository, AtividadeRepository>();
        #endregion

        services.AddDbContext<BANCO_DADOSWebAPIContext>(options =>
                options.UseSqlServer(ConfigurationManager.ConnectionStrings["Banco_Dados"].ToString()));
    }

    public void ConfigureDependencyInjection(HttpConfiguration config, UnityContainer container)
    {
        container.RegisterType<IContextService, ContextService>(new HierarchicalLifetimeManager());

    }

    public void ConfigureOAuth(IAppBuilder app, IProfissionalApplication usuarioApplication, ISistemaContextoApplication sistemaContextoApplication)
    {
        var oAuthServerOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/security/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
            Provider = new SimpleAuthorizationServerProvider(usuarioApplication, sistemaContextoApplication)
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(oAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }


}

}

  • Hello, is it a new or legacy application? Do you need to use OWIN in ASP.NET Core? Since it was rebuilt using OWIN specifications and with modifications/enhancements.

  • Hi Rafael, thanks for your attention. But it’s a legacy application, but it only had startup.Cs configured and another class with an interface .

  • Hello, try adding the app.Useowin(), maybe that’s what’s missing to inject the requested service.

  • I didn’t even have the option to import the library if I had this option, but in my project dependencies I have Microsoft.Owin.

  • Hello, @J.Moura. Try to change the position of the "Configureservices" method. Leave it as the first method. As in this example from Microsoft.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.