Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

Problems with "System.MissingMethodException: 'No parameterless constructor defined for type XXX'" in .Net Core 3.1

Hi I have a doubt about how implement correctly the followin code:

My Controller:

 [Route("api/[controller]")]
    [ApiController]
    public class TerminalsController : ControllerBase
    {
        private readonly IServiceWrapper _service;

        public TerminalsController(IServiceWrapper service)
        {
            _service = service;
        }

        [HttpPost]
        public async Task<ActionResult> Post([FromBody] Message object)
        {
            try
            {

                Result result = await _service.Terminal.UpsertInfo(ternminalObject);

                if (result.shopId != -1 || result.deviceId != -1 || result.companyId != -1)
                {
                    return Ok(result);
                }
                else
                {
                    return BadRequest("Can not save info from session on database");
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Internal server error");
            }
        }
    }

And the code of my serivice:

public class TerminalService : ITerminalService
    {
        private readonly IRepositoryWrapper _repository;

        public TerminalService(IRepositoryWrapper repository) 
        {
            _repository = repository;
        }

        public async Task<Result> UpsertInfo(SessionMessage ternminalObject)
        {
            try
            {
                // Do dark things....

                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }

The service use several things for insert or update in several db tables.

and, finally, my factory:

 public class DbClientFactory<T>
    {
        private static Lazy<T> _factoryLazy = new Lazy<T>(
            () => (T)Activator.CreateInstance(typeof(T)),
            LazyThreadSafetyMode.ExecutionAndPublication);

        public static T Instance
        {
            get
            {
                return _factoryLazy.Value;
            }
        }
    }

The factory instace the service and the repositories.

Well, this code, fail and throw the error:

System.MissingMethodException: 'No parameterless constructor defined for type TerminalsController'

Ok, the only way that I Found was this: No parameterless constructor defined when accessing web service

I mean, put public TerminalService() : this(new RepositoryWrapper()) { } in TermialService.

My doubt is, ?it this correct? I mean... I want that all go trow Interfaces, and I'm not sure if this "new RepositoryWrapper()" break this tarject

Im not sure if I make the question in the correct way... anyway, if you need more code, I will write here, I have written only what I considered necessary.

EDIT

This is my StartUp.cs:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            SqlHelper.connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureCors();
            services.AddMvc();
            services.ConfigureServiceWrapper();
            services.ConfigureRepositoryWrapper();
            services.AddControllers().AddNewtonsoftJson();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseStaticFiles();
            app.UseCors("CorsPolicy");
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.All
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

The ConfigureRepositoryWrapper and the ConfigureServiceWrapper are in the ServiceExtensions.cs:

 public static class ServiceExtensions
    {
        public static void ConfigureCors(this IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod());
            });
        }
        public static void ConfigureRepositoryWrapper(this IServiceCollection services)
        {
            services.AddScoped<IRepositoryWrapper, RepositoryWrapper>();
        }
        public static void ConfigureServiceWrapper(this IServiceCollection services)
        {
            services.AddScoped<IServiceWrapper, ServiceWrapper>();
        }
    }

The implement of ServiceWrapper is:

 public class ServiceWrapper : IServiceWrapper
    {
        private ITerminalService _terminal;

        public ITerminalService Terminal {
            get
            {
                if (_terminal == null)
                {
                    _terminal = DbClientFactory<TerminalService>.Instance;
                }
                return _terminal;
            }
        }
    }

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To sum up here, although the exception took place in controller, but with the code snippet provided by OP, we finally locate the error in the implement of ITerminalService.

Just using FormatterServices.GetUninitializedObject rather than Activator.CreateInstance to create instance can solve it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...