0

I'm trying to refactoring MVC after core migration to 3.1; I converted Startup like this (LightInject):

public Startup(IWebHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

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

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.LoginPath = "/signin";
            options.LogoutPath = "/signin";
            options.AccessDeniedPath = "/access-denied";
           // AutomaticAuthenticate = true,
            // AutomaticChallenge = true
        });

        services
            .AddControllersWithViews()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddFluentValidation(configuration =>
            {
                configuration.RegisterValidatorsFromAssemblyContaining<Startup>();
                configuration.RegisterValidatorsFromAssemblyContaining<AgentModel>();
            })
            .AddMappers(configuration =>
            {
                configuration.RegisterMappersFromAssemblyContaining<Startup>();
            });


        services.AddSingleton<IConfigurationRoot>(Configuration);

        services.AddAuthorization(options => { options.AddPolicy("Enabled", policy => policy.Requirements.Add(new UserEnableRequirement())); });

        services.AddSingleton<IAuthorizationHandler, UserEnableHandler>();

        // Register the IConfiguration instance which MyOptions binds against.
        services.Configure<SettingsModel>(Configuration);

        var container = new ServiceContainer();
        container.RegisterModule<DependencyInjectionModule>();

        return container.CreateServiceProvider(services);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        using (var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
            builder.AddDebug();
        }
        ))
        { }
        // Configuration.GetSection("Logging")
        if (env.IsDevelopment() || env.IsEnvironment("Local"))
        {
            app.UseDeveloperExceptionPage();
            //app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        

        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

        // app.UseHttpsRedirection(); doesn't work 
        app.UseStaticFiles();
        app.UseRouting();
        app.UseFileServer();

        app.UseAuthentication();
        app.UseAuthorization();
        

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });

    }

This is my Program

public static void Main(string[] args)
    {
        Host.CreateDefaultBuilder()
       .ConfigureWebHostDefaults(webBuilder => webBuilder
       .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseUrls("http://0.0.0.0:81")
            .UseIISIntegration()
            .UseStartup<Startup>()).Build().Run();
    }

It returns this error: System.NotSupportedException: 'ConfigureServices returning an System.IServiceProvider isn't supported.'

According to this, I have to use Autofac instead of IServiceProvider, but I have no idea about how to organize container, and so the rest. I tried twice, but the error is the same. So, how should I refactor the Startup file? Also, is there a way to fix this without using Autofac?

Kred
  • 319
  • 3
  • 12
  • 2
    `ConfigureServices()` in asp.net core 3 doesn't return `IServiceProvider` anymore it's `Void` now. If you're using LightInject i suggest looking at the documentation at their [site](https://www.lightinject.net/microsoft.aspnetcore.hosting/) – HMZ Jul 15 '20 at 18:00
  • Note: `Autofac` and `LightInject` are both DI containers so they share the same purpose as far as i know. – HMZ Jul 15 '20 at 18:06

1 Answers1

1

I had the same problems running LightInject on .NET CORE MVC 3.1.

I managed to get working versions of the code.

Need to add ConfigureContainer()*

public void ConfigureContainer(IServiceContainer container)
{
    container.RegisterFrom<CompositionRoot>();
}

My installed packages. Maybe not all of them are needed.

LightInject
LightInject.Microsoft.DependencyInjection
LightInject.Microsoft.Hosting

Startup.cs

using Project.Web.DI;
using LightInject;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Project.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureContainer(IServiceContainer container)
        {
            container.RegisterFrom<CompositionRoot>();
        }

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

            services.AddMvc(option =>
                {
                    option.EnableEndpointRouting = false;
                })
                .AddControllersAsServices()
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); ;

        }

        public void AddConnectionDb(IServiceCollection services)
        {
            services.AddDbContext<CacheContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("ProjectConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthorization();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "Default",
                    template: "{controller=Home}/{action=Index}/{id?}",
                    defaults: ""
                );
            });
        }
    }
}

Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace Project.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseLightInject()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

CompositionRoot.cs

using LightInject;

namespace Project.Web.DI
{
    public class CompositionRoot : ICompositionRoot
    {
        public void Compose(IServiceRegistry serviceRegistry)
        {
            serviceRegistry.Register<IUserRepository, UserRepository>();
            serviceRegistry.Register<IActRepository, ActRepository>();
        }
    }
}
Nikita
  • 64
  • 10