I am trying to setup my own Service Collection like so:
public static void AddMyServices(this IServiceCollection services)
{
services.AddServerSideBlazor();
//services.AddTransient<IMyService, MyService>();
}
I can't figure out how to get this running, I tried adding several NuGet References but none does work. e.g. Microsoft.AspNetCore.Components.Web to get AddServerSideBlazor(); working.
I want to use it like this in my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMyServices();
}
The Error I get:
'IServiceCollection' does not contain a definition for
'AddServerSideBlazor' and no accessible extension method
'AddServerSideBlazor' accepting a first argument of type
'IServiceCollection' could be found (are you missing a using directive
or an assembly reference?)
Edit:
After some more looking into it I think the correct package is
Microsoft.AspNetCore.App.Ref but adding it via NuGet gives me this error:
The package Microsoft.AspNetCore.App.Ref 5.0.0 has a package type
DotnetPlatform that is incompatible with this project.
You will need to Extend the IServiceCollection.
public static Microsoft.Extensions.DependencyInjection.IServerSideBlazorBuilder AddServerSideBlazor (this Microsoft.Extensions.DependencyInjection.IServiceCollection services, Action<Microsoft.AspNetCore.Components.Server.CircuitOptions>? configure = default);
found https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.componentservicecollectionextensions.addserversideblazor?view=aspnetcore-5.0
Related
I have a WEB API running on.Net5 for a while with the OData package.
Recently I've started to undertake the upgrade for .Net6 work but OData compatibility is broken at first. I needed to upgrade the OData package as well from v7 to v8.
After the upgrade first, my package references were broken so I've changed them from;
"using Microsoft.AspNet.OData;"
to
"using Microsoft.AspNetCore.OData;"
Now that resolved many of the errors, but coming back to my OData Config, my
services.AddOData();
has started to throw the error of "IServiceCollection' does not contain a definition for 'AddOData' and the best extension method overload 'ODataMvcBuilderExtensions.AddOData(IMvcBuilder)' requires a receiver of type 'IMvcBuilder'"
After some research, I've changed that to AddControllers first "services.AddControllers().AddOData();" and now my config file is like this;
public static void SetupOData(this IServiceCollection services)
{
// OData Support
//services.AddOData();
services.AddControllers().AddOData();
// In order to make swagger work with OData
services.AddMvcCore(options =>
{
foreach (OutputFormatter outputFormatter in options.OutputFormatters.OfType<OutputFormatter>().Where(x => x.SupportedMediaTypes.Count == 0))
{
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
foreach (InputFormatter inputFormatter in options.InputFormatters.OfType<InputFormatter>().Where(x => x.SupportedMediaTypes.Count == 0))
{
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
}
});
}
However after adding Config to the Startup with
// OData
services.SetupOData();
and
app.UseEndpoints(endpointRouteBuilder =>
{
endpointRouteBuilder.MapControllers();
// OData configuration
endpointRouteBuilder.EnableDependencyInjection();
endpointRouteBuilder.Filter().Select().Count().OrderBy();
});
I am getting error on EnableDependencyInjection() "'IEndpointRouteBuilder' does not contain a definition for 'EnableDependencyInjection' and no accessible extension method 'EnableDependencyInjection' accepting a first argument of type 'IEndpointRouteBuilder' could be found (are you missing a using directive or an assembly reference?)
So my OData usage is taking the non-EDM route and tried to implement that as simple as possible. But now after the upgrade, I am completely confused and or blinded right now. Can you help me get through this?
So an update;
Changing the OData config worked for me;
Instead of adding Odata first;
services.AddOData();
I pulled it inside the MvcCore;
services.AddMvcCore(options =>
{
foreach (OutputFormatter outputFormat ......."odatatestxx-odata"));
}
}).AddOData();
And then instead of using DI on endpointRouteBuilder, just kept MapControllers as;
endpointRouteBuilder.MapControllers();
Im trying to add roles functionality to my app but I'm getting an error message that I don't really understand or know how to fix it.
Im trying to add The IdentityRole to services.AddIdentityCore but getting an error message:
"'IServiceCollection' does not contain a definition for 'AddIdentityCore' and no accessible extension method 'AddIdentityCore' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) [API]csharp(CS1061)
Does anyone know how to implement it right?
What causes this issue ?
Thanks so much for the help
The solution is simple. Try this code like below:-
Your AppUser.cs model:-
public class AppUser:IdentityUser
{
...
}
Your startup.cs file:-
services.AddIdentity<AppUser, IdentityRole>(options=> {
options.Password.RequireDigit = false;
...
})
.AddEntityFrameworkStores<DataContext>()
.AddDefaultTokenProviders();
Try exact same code as above.It will resolve your issue.
I have a multi layered project with a web API project and a library project. Both projects rely on AutoMapper (and AutoMapper extensions for Microsoft.Extensions.DependencyInjection). Based on this
https://docs.automapper.org/en/latest/Dependency-injection.html#asp-net-core
in the Startup file I'm setting up AutoMapper for all the layers
Assembly apiAssembly = Assembly.GetExecutingAssembly();
Assembly myLibraryAssembly = Assembly.Load("MyLibrary");
services.AddAutoMapper(apiAssembly, myLibraryAssembly);
As you can see here, the API project needs to know about all the referenced library projects by loading them via name. I would prefer a way that every project is able to register itself. Based on this sample code
https://github.com/jasontaylordev/CleanArchitecture/blob/master/src/Application/DependencyInjection.cs
I created such a file in my library project
public static class DependencyInjection
{
public static IServiceCollection AddMyLibrary(this IServiceCollection services)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly(); // MyLibrary assembly
services.AddAutoMapper(executingAssembly);
// ... setup other services
return services;
}
}
and in the API project I can now do this
Assembly executingAssembly = Assembly.GetExecutingAssembly();
services.AddAutoMapper(executingAssembly);
services.AddMyLibrary();
The code seems to work fine but AddAutoMapper will be called twice. Once for the API assembly and once for the library assembly. Should I stick to the first approach because AutoMapper should only be added once or is it fine to separate it?
The accepted answer was correct at the time but it would appear that things have changed in the recent past.
The AutoMapper.Extensions.Microsoft.DependencyInjection package has been updated to allow the call to AddAutoMapper() multiple times.
See PR Use Microsoft.Extensions.Options to configure AutoMapper for details. You will need to update the package to version 8.0.0 or higher to use it.
The code seems to work fine but AddAutoMapper will be called twice. Once for the API assembly and once for the library assembly. Should I stick to the first approach because AutoMapper should only be added once or is it fine to separate it?
You should stick to the first approach, because AddAutoMappper does nothing when called for the second, third etc. time, thus profiles and other AM related types from the assemblies passed to these calls won't be registered.
It can be seen in the beginning of the implementation of the private method which is called by all public AddAutoMapper overloads:
private static IServiceCollection AddAutoMapperClasses(IServiceCollection services, Action<IServiceProvider, IMapperConfigurationExpression> configAction,
IEnumerable<Assembly> assembliesToScan, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
{
// Just return if we've already added AutoMapper to avoid double-registration
if (services.Any(sd => sd.ServiceType == typeof(IMapper)))
return services;
followed by the actual registration code, which at the end registers IMapper.
Currently there is an open issue Allow usage of Options Pattern to configure AutoMapper #132 with exactly the same concerns as yours.
You can use abp moudule system to make the library register for themselves.
The doc is here: https://docs.abp.io/en/abp/latest/Module-Development-Basics
But the framework is a little heavy.If you don't want to use it,
I think you can do it this way: every library register the automapper itself ,and call the other library's register function it depends on.
Each library can add a helper class to do the registration
public static class ApiRegisterHelper
{
public static Assembly GetAssembly()
{
return Assembly.GetExecutingAssembly();
}
public static IServiceCollection AddLibrary(IServiceCollection services)
{
Assembly executingAssembly = GetAssembly();
services.AddAutoMapper(executingAssembly);
DaoRegisterHelper.AddLibrary(services);
return services;
}
}
public static class DaoRegisterHelper
{
public static Assembly GetAssembly()
{
return Assembly.GetExecutingAssembly();
}
public static IServiceCollection AddLibrary(IServiceCollection services)
{
Assembly executingAssembly = GetAssembly();
services.AddAutoMapper(executingAssembly);
OtherRegisterHelper.AddLibrary();
return services;
}
}
I havn't tested it,but it might be work.Hope it helps.
What am I using:
.NET Core SDK 3.0.100
Visual Studio Community 2019 Version 16.3.2
I created a new ASP.NET Core Web API project targeting netcoreapp3.0 and I get the following error:
The type or namespace name 'CreateDefaultBuilder' does not exist in the namespace 'Template.Host' (are you missing an assembly reference?)
Take another look at the error message:
The type or namespace name 'CreateDefaultBuilder' does not exist in the namespace 'Template.Host'...
When you write Host.CreateDefaultBuilder in a namespace of Template.Host, the compiler assumes you mean Template.Host.CreateDefaultBuilder.
There's a few options for fixing this:
Nest the using statement inside of your namespace:
namespace Template.Host
{
using Microsoft.Extensions.Hosting;
// ...
}
Alias the Microsoft.Extensions.Hosting.Host type inside of your namespace:
namespace Template.Host
{
using Host = Microsoft.Extensions.Hosting.Host;
// ...
}
Use the fully qualified name for the Host type:
Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
Host represents the Generic Host and is preferred over WebHost in ASP.NET Core 3.0+.
UPDATE: I am of such a lowly SO status I can’t comment on Kirk’s post. I wasn’t aware of Host being the preferred in 3.0. Anyway, Kirk’s answer should be the correct one
You should be using WebHost (not Host) as follows:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
I'm following the next tutorial of IdentityServer4 implementation for API , but I can't call the method AddJsonFormatters() to services.AddMvcCore().
I'm currently configuring the API from an empty template in ASP.NET Core 3.0.0
I have added NuGet package Microsoft.AspNetCore.Mvc.Formatters.Json with no results.
Also, I understand that using AddMvc() instead of AddMvcCore() would be a partial solution but I can't use AddAuthorization() on AddMvc()
//code extracted from the link
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
}
}
This is the error message I see above:
'IMvcCoreBuilder' does not contain a definition for
'AddJsonFormatters' and no accessible extension method
'AddJsonFormatters' accepting a first argument of type
'IMVCoreBuilder' could be found (are you using a missing directive or
an assembly reference?)
Is this the method? Should I send an MVCCoreBuilder? How do I do that? MvcJsonMvcCoreBuilderExtensions.AddJsonFormatters Method
When you call services.AddMvc() you get an IMvcBuilder.
if you want to add more output or input formatters, the IMvcBuilder has an extension method that you can call AddMvcOptions bellow you have an example of an XmlDataContractSerializerOutputFormatter that was added
mvcBuilder.AddMvcOptions(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
options.InputFormatters.Add(new XmlDataContractSerializerInputFormatter(options));
Mvc already has a JsonOutputFormatter ,so inside of the AddMvcOptions you can get it and also and add your own custom mediatypes if you need it.
var jsonOutputFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();
if (jsonOutputFormatter != null)
{
jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.Vnd+json.all);
jsonOutputFormatter.SupportedMediaTypes.Add(HttpMediaTypes.ApplicationOctetStream);
}
As I understood, there is not class MvcJsonMvcCoreBuilderExtensions in .NET Core 3.0 yet.
Eventually I just added -f parameter when I was created the Api project:
dotnet new web -n Api -f netcoreapp2.2
instead of
dotnet new web -n Api
It makes the Api project for .NET Core 2.2 so you can read the tutorial.
I was having the same issue. I found that I was on the wrong tutorial for implementing it with the current versions of dotnet core. The comment made by -AnorZaken helped:
Check the tutorial again, it has been updated to NetCore3
Look at the top of the sidebar on the tutorial page. If it says "Release" under the IdentityServer4 title, that won't work.
There is a dropdown at the bottom of the sidebar where you can select "3.1" instead.
Use this:
If MVC
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
.....
.....
if it is API than use
services.AddControllersWithViews().AddNewton ......