Asp.net api dependency injection location - c#

I am following a tutorial on asp.net web api and mongodb here and on step 4 it talks about dependency injection and adding it to the start.cs in the ConfigureServices() method, however this doesnt seem to exist anymore. My web api templates startup.cs looks something like this...
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
So my question is where do I inject my DataAccess class to my web api project as a service? Thanks in advance.
As requested here is my api structure
under LGR.API is the auto generated folders and classes created by visual studios and starting a LGR.Datamodel is my custom class with my api stuff. Really new here... not sure if this correct at all. Feel free to critique with best practices as necessary

It looks like you've created an ASP.NET application, and your tutorial is for ASP.NET Core. Recreate your project and pick the "ASP.NET Core Web Application" template.

Related

Use .NET Core MVC Project as a middleware

I have one .NET Core MVC application that provides a dashboard to represent statistics and so on.
I would like to use this MVC application as a Middleware so that I can use it the same way than Hangfire, NSwag and so on.
So in my main project I would like to do the following:
Import my NuGet package (the Dashboard MVC Application)
app.UseDashboard(options...)
I already have a Middleware class inside my Dashboard MVC App with the following:
public static class JwtDashboardMiddleware
{
public static void UseMyDashboard(this IApplicationBuilder app)
{
// 1. Provide an endpoint(/ myDashboard)
app.Map("/myDashboard", app =>
app.Run(async (context) =>
{
string message = "Hello Middleware";
//2. This page contains a simple form, Submit the form to redirect to another for
await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(message));
}));
}
}
I also created a NuGet Package with the Dashboard MVC App and it is working, but in the Main Application and also in the in the Dashboard MVC App it cannot access the Views and so on.
So from the Middleware inside the Dasboard MVC app how do I access the controllers and how do I integrate this with other MVC applications to achieve the points mentioned above?
Btw. I also tried to redirect to the controller view, but the view is just not accessible ? Do I need to compile the views to be included in the NuGet package or how does this work?
The main question is: How do I use my controllers and views inside the Middleware?
You cannot embed whole MVC application into one static route.
NSwag for example, on the /swagger endpoint, serves a static html file, which is basing on swagger.json file generated from the API itself

Asp.net Identity with Code First in Asp.net MVC application using class library

I am trying to implement Identity Authentication using class library with code first in my asp.net MVC application.
At first I created test project with default selection "Individual User Accounts"
Using default templates with identity i found It creates some of the default files/classes like
IdentityModel.cs, IdentityConfig.cs(in APP_Start) & Startup.cs(partial class with anothe file in APP_Start Startup.Auth.cs),
AccountViewModel.cs, ManageViewModel.cs .
After that I searched for how to use identity related classes in Class Library, and using suggestions moved
all of above in class library project Names TestLib.
I have put IdentityModel.cs, IdentityConfig.cs in Model folder in TestLib and Startup in root of TestLib and change respective references in my web project.
I have removed OwinStartupAttribute from Startup.cs in web project and added OwinStartupAttribute to Startup.cs in TestLib.
And all seems to be working well also code first, but here I have some questions whether I am doing things correctly or not.
1) Is it OK to have Startup.cs in class library?
2) At now I have other models for my database in "ApplicationDbContext"
class, which creates table correctly in database.
So
1.Is it OK to use ApplicationDbContext instead of my CustomContext & can I
use this class library with my other application like some
windows application which do not use identity? OR
Should I keep separate context? OR
Is it possible to remove ApplicationDbContext and use my CustomContext?

Hosting an asp.net and a web api my self

Basically I have an exe, that controls a pizzaria, it should be extended to allow users to choose a pizza slice from the web. The application I have, keeps track of what slices are available at the moment, and only show them on the site.
I've made an asp.net web api project and am hosting that inside my application.
(Owin, self hosting asp.net web api;-) My problem is how to configure the IAppBuilder, to go the normal MVC steps looking for my site, when the url, requested didn't go to an api controller.
public class Startup {
public static void Configuration(IAppBuilder app) {
app.UseStaticFiles();
var apiConfig = new HttpConfiguration();
apiConfig.MapHttpAttributeRoutes();
app.UseWebApi(apiConfig);
// THIS IS WHERE I NEED THE app to look through
// my MVC controllers, to get the view..
app.Run(async context => {
await context.Response.WriteAsync(" My First dummy OWIN App");
});
}
}
(I think I just need to figure out how to get the mvc controllers to get the request.. )
Thanks any help will be appreciated, with this, my first asp/web project in 15 years..

How ASPNET CORE start up to listen httprequest?

well, I am now learning aspnet core , I can't understand when does the application start its server(like IIS or KestrelServer),and how the server listen the httprequest and forwards the request to the application. can anybody help me? thanks
Well, let's start from beginning (As I couldn't figure out your knowledge about C#)
Every C# application must contain a single Main method specifying where program execution is to begin, so there it is, by default the templates have a Class Program where you can set the type of WebServer that you'll use, and tell the server to start listening for HTTP requests, something like:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseKestrel()
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
host.Run();
}
In AspNetCore and even in AspNet (MVC or WebApi) you can (and should) use OWIN (aka Katana or vNext, that are Microsoft's OWIN implementations for AspNet and AspNetCore respectively).
OWIN represents a Interface (just a specification), that tell how WebServers should comunicate with WebApplications. Normally it handle the Http Requests to a pipeline that you can plug Middlewares, like Authentication/Authorization, Log, Error Handlings and so on, and in the end of the pipeline you should plug your Web Application.
In AspNetCore you set your Middleware Pipeline by using UseStartup<MyStartupClass> in your Host configuration see Main method above and simple as that your Pipeline will handle every HttpRequest.
When building a MVC applications in AspNetCore (.UseMvc()) you are setting a middleware that tells your application to look for classes that inherit from Microsoft.AspNetCore.Mvc.Controller to look for RESTful entry points (HTTP GET, POST...)
This is just a simple overview, and you can learn a lot more looking in the documentation of this technologies. Just search for tags like Katana, vNext, OWIN, OWIN Middleware, OWIN Pipeline...
ASP.NET Core application anatomy is discussed here at this asp.net core introduction.
Some important text that answers your question is as follows from the tutorial:
An ASP.NET Core app is simply a console app that creates a web server in its Main method. Main uses WebHostBuilder, which follows the builder pattern, to create a web application host. The builder has methods that define the web server (for example UseKestrel) and the startup class (UseStartup). In the example above, the Kestrel web server is used, but other web servers can be specified. The Startup class is where you define the request handling pipeline and where any services needed by the app are configured. The Startup class must be public and contain the following methods:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
}
}
I guess this will help you to understand how asp.net core handles Http requests.
Thanks

MVC3 & EF. Interface for TDD

Can somebody please explain:
I am using MVC3/C#/Razor to build a project to get used to using MVC.
I am using the inbuilt account controller.
I am storing the account data in my local SQL database using Entity Framework to connect.
How can I easily generate interfaces for EF?
SO FAR I am using the plugin from: http://blog.johanneshoppe.de/2010/10/walkthrough-ado-net-unit-testable-repository-generator/#step1
This allows me to have an interface for my entities already created.
However, I know that I have to change my HomeController arguments to accept either the real repository or a fake one for testing.
I am completely lost!
Have a look at these. They will help and get you started :
http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
http://msdn.microsoft.com/en-us/library/gg416511(VS.98).aspx
For dependency injection, you can follow these steps :
Install-Package Ninject.MVC3 with nuget to your ASP.NET MVC 3 project (if your app is on version 3). This will basically do everything.
Then have the following on your controller :
private IMyModelRepository _myrepo;
public HomeController(IMyModelRepository myrepo)
{
_myrepo = myrepo;
}
Go to NinjectMVC3.cs file inside App_Start folder and add the following code to inside RegisterServices method :
private static void RegisterServices(IKernel kernel) {
kernel.Bind<IMyModelRepository>().To<MyModelRepository >();
}
Fire up your app and you should be up and running.

Categories

Resources