0

I'm not really familiar that much about ASP.Net Core. My issue is I have this controller like the following

[Route("api/[controller]")]
public class MyController : MyBaseService
{
    private IWebHostEnvironment _env;
    private IAuth _auth;

    public MyController(IWebHostEnvironment env,
                                IAuth auth) : base(auth)
    {
        _hostingEnv = env;
        _auth = auth;
    }

IAuth is registered as Scoped service in Startup.cs like services.AddScoped<IAut, Auth>(); If I call the controller, the auth doesn't have values. I believe this is because of the lifetime of the service, am I right? If that is so. I just want to populate it with values whenever the controller is being called. Is there such a way like getting the values from IAuth then automatically insert it in the level of Startup.cs something like this lambda function?

app.UseRequestLocalization(new RequestLocalizationOptions
{
      SupportedCultures = "String value here.",
});

If my imagination is wrong just correct me as I said I'm not that familiar with ASP.Net Core.

user3856437
  • 2,071
  • 4
  • 22
  • 27
  • did you see this? https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#lifetime-and-registration-options could be the answer is in there – sommmen May 13 '20 at 09:52
  • I see a problem: the name of the constructor must be the same name as the controller class. MyController is the name of your controller but your constructor is called FileUploadController. You call base but i don't think it knows about IAuth..also what does IAuth do? the dependency injection works like when you request the interface you get an implemplementation of it. So that Auth class is where you have your data and methods ready to use in your controller by using IAuth. It will have what data you have in your Auth class. – Johan Herstad May 13 '20 at 10:09
  • Sorry @Johan, it was a mistyped. I already corrected it. – user3856437 May 13 '20 at 11:35
  • @sommmen haven't read it yet. I'll check that. – user3856437 May 13 '20 at 11:35

2 Answers2

0

If you have some properties on the Auth service that you need to be set during the registration, you can use the AddScoped like this:

services.AddScoped<IAut, Auth>(sb => new Auth() { SomeValue = "value" });
Jakub Kozera
  • 3,141
  • 1
  • 13
  • 23
0

The method @kebek provided is in the right direction, but you need to populate the data according to the structure in your Auth class.

You can refer to this.

Here is my demo:

public interface IAuth
    {
        string MyValue{ get; }
    }

 public class Auth: IAuth
    {
        string _value; 
        public Auth(string value)
        {
            _value = value;
        }

        public string MyValue=> _value;
    }

In startup.cs:

 services.AddScoped<IAuth, Auth>(provider => new Auth("Your value"));

Here is the result:

enter image description here

LouraQ
  • 6,443
  • 2
  • 6
  • 16