Implementing Interface and initialise it in MVC Controller - c#

I am working with the web application and I have a class which have all the business logic which implement Interface. I am trying to referenced Interface and class in startup.cs and trying to initialise in Controller. My business logic class is like this:
public class User_MasterDataAccesss: IUserMasterRepository
{
.... business logic
public int validate(string name)
{
...... doing something
}
}
I have an interface which have definition for the validate function like this
public interface IUserMasterRepository
{
int validate(string name);
}
I am trying to bind the interface in startup.cs like this
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// services.AddMvc();
// Add application services.
services.AddSingleton<IUserMasterRepository, User_MasterDataAccesss>();
}
}
and I am trying to initialise the interface in controller like this
public class AuthenticationController : Controller
{
private IUserMasterRepository UserMasterRepository;
public AuthenticationController() { }
public AuthenticationController(IUserMasterRepository userMasterRepository)
{
this.UserMasterRepository = userMasterRepository;
}
......... action result actions which is using the UserMasterRepository
}
My problem is as follows:
Constructor is not executing and as a result UserMasterRepository is null when accessing from action.
services.AddMvc(); in startup.cs is doesnot exist
I know I can achieve my requirement by using Ninject but I want to use startup.cs file for that matter
I do not want to use new key word in controller.
How can I achieve this? Where I am wrong?

Installing ASP.NET 5 runtime and tooling solve my problem.

Related

Retrieve Service and use it in some arbitrary class in net core

There are plenty of examples how to set controllers to use services etc. But what about plain old class? Lets use some simple configuration service
JSON
{
....,
"AppSettings": {
"SchemaFile": "some file name.xml"
}
}
POCO
public class AppSettings
{
public string SchemaFile { get;set; }
}
In startup.cs
public void ConfigureServices(IServiceCollection services)
{
IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
. . . .
}
This is the point where all examples move directly to the controller. But we are going to have plenty of code outside controller. What I need is to access this service using provider.GetService(typeof(T)) or provider.GetRequiredService(typeof(T)), from, lets say a static class
internal static MyClass
{
internal static void DosomeThing()
{
// acquire my service
// use it to retrieve some value
// continue with my logic
}
}
Thanks
Just as the services can be injected into controllers, so too can they be injected into other classes.
static classes however to not lend themselves well to dependency injection by default.
Instead of using a static class, make a regular class and explicitly depend on the desired service via constructor injection
internal class MyClass : IMyService {
readonly AppSettings settings;
public MyClass(AppSettings settings) {
this.settings = settings;
}
internal void DosomeThing() {
// retrieve some value from settings
// continue with my logic
}
}
You can then register your desired POCO and utilities with the service container
public void ConfigureServices(IServiceCollection services) {
AppSettings appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
services.AddSingleton(appSettings);
services.AddSingleton<IMyService, MyClass>();
//. . . .
}
Inject your service where it is needed and it will have access to the POCO when being resolved for injection.
There really is no need to be passing IServiceProvider around as that can be seen as a code smell.
Simplifying your design to follow explicit dependency principle should make your code more SOLID and easier to follow and maintain.
You should pass AppSettings as parameter from the caller method
public class HomeController : Controller
{
public HomeController(AppSettings settings)
{
this.Settings = settings;
}
private AppSettings Settings { get; }
public IActionResult Index()
{
MyClass.DosomeThing(this.Settings);
}
}
internal static MyClass
{
internal static void DosomeThing(AppSettings settings)
{
// acquire my service
// use it to retrieve some value
// continue with my logic
}
}

One service, two instances, how to configure with ASP.NET Core DI?

With ASP.NET Core's Options pattern one can create Service and register it with two separate calls.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyService>();
services.Configure<MyServiceOptions>(o => o.Param = 1);
services.AddMvc();
};
However, I am entirely unclear on how and if it is possible to instantiate two instances of a service and bind different options to them? i.e. given two specialisations of some base class, how do we share a single options class between them?
public class MyService {}
public class MyService1 : MyService {}
public class MyService2 : MyService2 {}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyService1>();
services.AddTransient<MyService2>();
// What goes here?
// config for instance 1
//services.Configure<MyServiceOptions>(o => o.Param = 1);
// config for instance 2
//services.Configure<MyServiceOptions>(o => o.Param = 2);
services.AddMvc();
};
Basically I want something like the IServiceCollection.AddDbContext extension method, but for services, and I've looked at the EF Core extension methods and I don't get them at all.
Going with #Kirk Karkin's advice -
public class MyServiceOptions
{
public int setting { get; set; }
}
public class MyService
{
public MyService(IOptions<MyServiceOptions> options)
{
// TODO: Capture options.
}
}
public class MyServiceOptions<TMyService> : MyServiceOptions
where TMyService : MyService
{
}
Now I can create instances of this service by extending it:
public class MyService1 : MyService
{
public MyService1(IOptions<MyServiceOptions<MyService1>> options>):base(options)
{
}
}
And then registering multiple instances is easy in Configure Services:
services.AddTransient<MyService1>();
services.AddScoped<MyService2>();
services.Configure<MyServiceOptions<MyService1>>(Configuration.GetSection("MyService1Settings"));
services.Configure<MyServiceOptions<MyService2>>(Configuration.GetSection("MyService2Settings"));

Asp.net Core 2 - How to use ServiceLocator in Asp.net Core 2.0

My Startup is like this :
public void ConfigureServices(IServiceCollection services)
{
// code here
Bootstraper.Setup(services);
}
And my Bootstraper class is like this :
public static partial class Bootstraper
{
// code here
public static IServiceCollection CurrentServiceCollection { get;set;}
public static IServiceProvider CurrentServiceProvider
{
get { return CurrentServiceCollection.BuildServiceProvider(); }
}
public static void Setup(IServiceCollection serviceCollection)
{
// code here
SetupLog();
InitializeCulture();
InitializeDbContexts();
RegisterDataModelRepositories();
}
and this is content of my RegisterDataModelRepositories():
CurrentServiceCollection.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
CurrentServiceCollection.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
in short : I just want to be able to use Service Locator in my methods without resolving dependency in class constructor ... is there any way around it ....
Dependency injection can also be done on a by action basis.
Referece Dependency injection into controllers: Action Injection with FromServices
Sometimes you don't need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices]
public IActionResult SomeAction([FromServices] IReportService reports) {
//...use the report service for this action only
return View();
}
Just make sure that the required services are registered with the service collection.
services.AddTransient<IDefAccidentGroupRepository>(p => new DefAccidentGroupRepository(ApplicationMainContextId));
services.AddTransient<IDefGenderRepository>(p => new DefGenderRepository(ApplicationMainContextId));
services.AddTransient<IReportService, ReportService>().
well , thanks for your help ...
There is a easier and better way for it , I just need to add another Service that use these repository and then resolve that service in my controller and let Asp.net Core 2.0 DI to solve the problem for me ...
public interface IActionService
{
IRepositoryA repA {get;set;}
IRepositoryB repB { get;set;}
DoTaskX();
DoTaskY();
}
then in my ActionService :
public class ActionService : IActionService
{
public IRepositoryA repA {get;set;}
public IRepositoryB repB { get;set;}
public ActionService (IRepositoryA rep_a , IRepositoryB rep_b ) {
repA = rep_a;
repB = rep_b;
}
DoTaskX(){
// do task using repository A and B
}
}
then I register IActionService in Startup.cs and resolve itin my ActionController and life become easier and code become cleaner ...
the solution was easy but I had to change my mindset to solve the problem ...

Unable to resolve service for type while attempting to activate

In my ASP.NET Core application, I get the following error:
InvalidOperationException: Unable to resolve service for type 'Cities.Models.IRepository' while attempting to activate 'Cities.Controllers.HomeController'.
I the HomeController I am trying to pass the Cities getter to the view like so:
public class HomeController : Controller
{
private readonly IRepository repository;
public HomeController(IRepository repo) => repository = repo;
public IActionResult Index() => View(repository.Cities);
}
I have one file Repository.cs that contains an interface and its implementation like so:
public interface IRepository
{
IEnumerable<City> Cities { get; }
void AddCity(City newCity);
}
public class MemoryRepository : IRepository
{
private readonly List<City> cities = new List<City>();
public IEnumerable<City> Cities => cities;
public void AddCity(City newCity) => cities.Add(newCity);
}
My Startup class contains the default-generated code from the template. I have made any changes:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
}
}
For the Dependency Injection framework to resolve IRepository, it must first be registered with the container. For example, in ConfigureServices, add the following:
services.AddScoped<IRepository, MemoryRepository>();
For .NET 6+, which uses the new hosting model by default, add the following in Program.cs instead:
builder.Services.AddScoped<IRepository, MemoryRepository>();
AddScoped is just one example of a service lifetime:
For web applications, a scoped lifetime indicates that services are created once per client request (connection).
See the docs for more information on Dependency Injection in ASP.NET Core.
We are getting this error in Entity frame work core database first approach. I followed below steps and error got resolved
Step 1: Check Your context class constructor should be like this
public partial class ZPHSContext : DbContext
{
public ZPHSContext(DbContextOptions<ZPHSContext> dbContextOptions)
: base(dbContextOptions)
{
}
}
Step 2: In Startup file
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ZPHSContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("BloggingDatabase")));
}
Step 3: Connection string in appsettings
"ConnectionStrings": {
"BloggingDatabase": "Server=****;Database=ZPHSS;Trusted_Connection=True;"
}
Step 4: Remove default code in OnConfiguring method in context class
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
Other answers are CORRECT, however I was spinning up a new asp.net core 2.1.x project and got this error.
Ended up being a typo by ME.
So in my Controller instead of Correctly using the Interface like this
public HomeController(IApplicationRepository applicationRepository)
{
_applicationRepository = applicationRepository;
}
My typo had me using ApplicationRepository instead of its interface IApplicationRepository
Notice below, and so with NO ERRORS spotting the missing "I" was fun :/
public HomeController(IApplicationRepository applicationRepository)
{
_applicationRepository = applicationRepository;
}
Thus the controller was not resolving the DI...
A method like this needs to be added to your Startup:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//...
// Add application services.
services.AddTransient<IRepository, MemoryRepository>();
//..
}
Services should be registered before used.
UPDATE:
If you do not want to use DI on your application, just create and instance of MemoryRepository on the constructor of HomeController, like this:
public class HomeController : Controller
{
private IRepository repository;
public HomeController()
{
repository = new MemoryRepository();
}
public IActionResult Index()
{
return View(repository.Cities);
}
}
You have to add your implementation to DI (Dependeny Injection) section. For .Net Core Mvc, it would be like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase()
);
services.AddScoped<IRepository, MemoRepostory>();
}
This may not be helpful for your code sample but in my case the same error was a result of a circular dependency.
you have to register your repository like this
services.AddSingleton<IRepository, MemoryRepository>();
In my case, I was trying to access context through constructor. like here;
private readonly Context _context;
public ImageController(Context context)
{
_context = context;
}
But When I tried to access the context just by creating an instance of class, it worked like here;
Context c = new Context();
For me I am using visual studio 2022 and .NET 6
the solution was add the following line in the Program.cs file :
builder.Services.AddSingleton<IHISInterface<UserDetails>, UserDetailsRepository>();
There is one more possibility that, You might have sent wrong variable in the place while writing this HTTPPOST last part code
mine is
var categoryMap = _mapper.Map(categoryCreate);
if(!_categoryRepository.CreateCategory(categoryMap))
{
ModelState.AddModelError("", "Something went wrong while saving");
return StatusCode(500, ModelState);
}
return Ok("Successfully created");
in the if condition I passed the category as parameter instead of categoryMap
so please cross check

Dependency Injection pass parameters by constructor

We have a project where we need to use DI and ASP Core.
I'm very new to this and have a question.
I have a controller named HomeController like this:
public class HomeController : BaseController {
private IOrderService _orderService;
public HomeController(IOrderService orderService) {
_orderService = orderService;
}
public IActionResult Index() {
var orders = _orderService.GetMyOrders();
return View(orders);
}
}
The code looks like this:
public class OrderService : BaseService, IOrderService {
public OrderService(IDataContextService dataContextService) {
_dataContextService = dataContextService;
}
public List<Orders> GetMyOrders() {
var orders = // do my code here which works fine!;
// here i need some code do check orders for delivery so
DeliveryService deliveryService = new DeliveryService(_dataContextService);
// update my orders and return these orders
return orders;
}
}
public class DeliveryService : BaseService, IDeliveryService {
public DeliveryService(IDataContextService dataContextService) {
_dataContextService = dataContextService;
}
public void MyMethod() {
}
}
public class BaseService {
protected IDataContextService _dataContextService;
}
Almost all my services have a constructor like the OrderService and DeliveryService. My question is, do I have to pass the _dataContextService every time, or is there a solution within the dependency pattern?
You should keep it the way you have it and asp.net core IoC will inject it for you, but make sure it is injected per request, this will help to insantiate only one context for each request and dispose it after the request is served.
You can register the context and services in the ConfigureServices method inside the Startup class as below
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
// Add application services.
services.AddTransient<HomeController>();
services.AddTransient<IOrderService , OrderService >();
services.AddTransient<IDeliveryService, DeliveryService>();
services.AddScoped<IDataContextService , YourDataContextService >();
}
The AddScoped method will create only one instance of the object for each HTTP request
If I understand correctly what you are asking, you are looking for an IoC container. .NET Core has built in support for dependency injection. Basically, you just indicate which implementation should be provided when an interface is requested. Then the container will instantiate the types for you. See for example https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection.
Hope that helps

Categories

Resources