简体   繁体   中英

Constructor of controller in MVC application

When is the constructor of controller class is called and how? I'm asking this because in an application that I am maintaining, constructor of controller is passed with Interfaces of dlls and they appear to be automatically initialized by some deafult method in Dll. Contoller looks like this:

private _clientdetails
public CleintController(IClientDetails clientdetails)
{
    _clientdetails = clientdetails
}
//here various members of clientdetails used via _clientdetails

This only appears to work when IClientdetails clientdetails is passed as a param to constructor otherwise I get error: Type passed as var . If I can see/know how constructor of controller is called, I can know how to pass this initialized interface to my other methods.

If I understood your question, You may pass an instanciation of a class detail which implements IClientDetails

public class detail : IClientDetails 
{
//detail class implementation
//interface method implementation
}

Usage

CleintController(new detail());

or

detail d = new detail(){ proper1 = value,....};
CleintController(d);

Editing

if you want to use a default implementation of the interface just add a default constructor in the controller , like this :

public CleintController()
{
    _clientdetails = new DefaultClass();
}

with DefaultClass is the default class that implements IClientDetails

Editing 2 *

To get all class that implements the interface as mentionned here : Getting all types that implement an interface

You can do this :

var type = typeof(IClientDetails);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

then you can easily identify which class (that implements IClientDetails) you need .

what you are asking is called dependency injection.

a simple example is here

basically you say your application where ever you saw this interface implement this class also every one of them has lots of options.

Just check your application start method and you will see some injections.

Bit late but for whoever who needs it: ASP.NET MVC allows you to specify which objects to automatically supply to the caller. Take a look at Startup.cs in your main root and you should see some code that looks like this:

public void ConfigureServices(IServiceCollection services)
{
    // Add application services.
    services.AddTransient<IDateTime, SystemDateTime>();
}

This bit of code will supply the caller of IDateTime with a new instance of SystemDateTime.

More info here: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM