I cannot get autofac to work, I have looked at this potentially duplicate question, but it doesn't help.
I am using the full .NET stack, DNX 4.5.1
I have included the following dependencies.
"dependencies": {
// matched latest autofac version with latest dependencyinjection version.
"Autofac": "4.0.0-beta8-157",
"Autofac.Framework.DependencyInjection": "4.0.0-beta8-157",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final" ...
And the following initialisation code.
// void?
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var container = new ContainerBuilder();
...
// compilation error here!
container.Populate(services);
}
I am receiving this error:
Error CS1503 Argument 2: cannot convert
from'Microsoft.Extensions.DependencyInjection.IServiceCollection' to
'System.Collections.Generic.IEnumerable<Microsoft.Framework.DependencyInjection.ServiceDescriptor>'
MuWapp.DNX 4.5.1 C:\MuWapp\Startup.cs 54 Active
For RC1 you will need to use the Autofac.Extensions.DependencyInjection package.
https://www.nuget.org/packages/Autofac.Extensions.DependencyInjection/
We renamed our package to align with Microsoft's rename to Microsoft.Extensions.DependencyInjection. It's been a moving target supporting the early DNX releases.
As I've mentioned in the comment, you should use compatible versions of all packages in your project.json. I see on their page: https://github.com/autofac/Autofac/releases that they have released version for RC1, however there is no Autofac.Framework.DependencyInjection for RC1, so if you require this package, you will be unable to run it.
I think you should use built-in dependency injection during your development untill there is RTM version and all of the third-party packages will become stable.
Build-in DI has functionality for injecting classes into controllers, properties as well as attributes, so unless you use some advanced scenarios in which autofac is necessary, you should stick to asp.net 5 DI.
Related
I've just upgraded my ASP web API project from .Net core 2.0 to 3.0. I was using
services.AddMvc()
.AddJsonOptions(options =>options.SerializerSettings.ContractResolver
= new DefaultContractResolver());
previously to ensure lower-casing of the serialized JSON.
After the upgrade to 3.0 I get this error:
Error CS1061 'IMvcBuilder' does not contain a definition for
'AddJsonOptions' and no accessible extension method 'AddJsonOptions'
accepting a first argument of type 'IMvcBuilder' could be found (are
you missing a using directive or an assembly reference?)
According to AddJsonOptions for MvcJsonOptions in Asp.Net Core 2.2 the AddJsonOptions extension method is/was provided by the Microsoft.AspNetCore.Mvc.Formatters.Json nuget package. I have tried installing/reinstalling this but still can't resolve the method. Interestingly, intellisense only shows Microsoft.AspNetCore.Mvc.Formatters.Xml when I try to add the using statement even though I added the Json nuget package.
Any ideas what is going on? The documentation for AddJsonOptions only goes up to .Net 2.2 so perhaps the method has been deprecated in 3.0 in favor of some other configuration mechanism?
As part of ASP.NET Core 3.0, the team moved away from including Json.NET by default. You can read more about that in general in the announcement on breaking changes to Microsoft.AspNetCore.App.
Instead of Json.NET, ASP.NET Core 3.0 and .NET Core 3.0 include a different JSON API that focuses a bit more on performance. You can learn about that more in the announcement about “The future of JSON in .NET Core 3.0”.
The new templates for ASP.NET Core will no longer bundle with Json.NET but you can easily reconfigure the project to use it instead of the new JSON library. This is important for both compatibility with older projects and also because the new library is not supposed to be a full replacement, so you won't see the full feature set there.
In order to reconfigure your ASP.NET Core 3.0 project with Json.NET, you will need to add a NuGet reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson, which is the package that includes all the necessary bits. Then, in the Startup’s ConfigureServices, you will need to configure MVC like this:
services.AddControllers()
.AddNewtonsoftJson();
This sets up MVC controllers and configures it to use Json.NET instead of that new API. Instead of controllers, you can also use a different MVC overload (e.g. for controllers with views, or Razor pages). That AddNewtonsoftJson method has an overload that allows you to configure the Json.NET options like you were used to with AddJsonOptions in ASP.NET Core 2.x.
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
This worked for me, while using .Net Core 3:
services.AddMvc().AddJsonOptions(o =>
{
o.JsonSerializerOptions.PropertyNamingPolicy = null;
o.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
Make sure that you installed the Microsoft.AspNetCore.Mvc.NewtonsoftJson package.
It's work for me, Install the NewtonsoftJson package from NuGet "dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson --version 3.1.0" version 3.1.0 working for ASP.NET Core 3.0 and use the Following Code-
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Hope it's Working Fine, Thanks.
This would help
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(options=> { options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
});
services.AddDbContext<PaymentDetailContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
This would help try Installing the Nuget Package
Microsoft.AspNetCore.Mvc.NewtonsoftJson
This worked for me, while using .Net Core 3:
click here
I have a .Net Core 2.2 class library that uses the CQRS pattern with MediatR. I add all my dependencies into a serviceProvider in Main and attach MediatR via:
serviceCollection.AddMediatR();
var serviceProvider = serviceCollection.BuildServiceProvider();
Everything works like a charm and I am able to send any of my commands or queries to MediatR without fail.
I want to use the same exact library in a WebApi (also .Net Core 2.2) and set up my serviceProvider the exact same way inside of the Startup.ConfigureServices() method and I get the following exception when calling any controller that uses MediatR:
InvalidOperationException: Handler was not found for request of type MediatR.IRequestHandler`2[Core.Application.Accounts.Queries.GetAccountListQuery,System.Collections.Generic.List`1[Core.Application.Accounts.Models.AccountViewModel]]. Register your handlers with the container. See the samples in GitHub for examples.
MediatR.Internal.RequestHandlerBase.GetHandler(ServiceFactory factory)
I was able to resolve the issue by explicitly adding each command or query prior to adding MediatR to the DI container:
services.AddMediatR(typeof(GetAccountListQuery).GetTypeInfo().Assembly);
services.AddMediatR();
But does this mean I have to register every single IRequest object in my library? How is MediatR able to register them for me in the Console app but not in the WebAPI? Is there a better method?
I have seen this post that recommends assembly scanning, however it perplexes me that my Console app seemed to do this automatically. Also I am not sure I want to move to Autofac just yet. I have seen some packages to help you do the same with the default ServiceProvider - however I really want to avoid adding extra dependencies unless absolutely necessary.
It should be enough to just have this:
services.AddMediatR(typeof(GetAccountListQuery));
or just
services.AddMediatR(typeof(Startup));
It works for me in ASP.NET Core 2.2. The project has these two NuGet dependencies:
MediatR version 6.0.0
MediatR.Extensions.Microsoft.DependencyInjection version 6.0.1
P.S. For those, who minuses - any class from assembly would work. I used GetAccountListQuery as an example because it is for sure inside the right assembly. See my comments below.
When setting up LightInject for an MVC controller I am getting an error when calling container.EnableMvc(); in the injector setup.
Error:
Method not found:
'Void LightInject.WebContainerExtensions.EnablePerWebRequestScope(LightInject.IServiceContainer)'
Source:
public static void Register() {
var container = new ServiceContainer();
container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();
WebContainerExtensions.EnablePerWebRequestScope(container);
container.RegisterControllers();
container.Register<ISomeClass, SomeClass>();
container.EnableMvc();
}
Additional Information:
I am running the code locally through Visual Studio
The project is 4.5
My OS is Windows 10 (framework 4.5)
In the past when I have setup LightInject I have set the scope lifetime manually but the documentation, for general setup and MVC specific examples, has since changed. I came across one thread that mentioned this could be an issue with not including LightInject.Web as a dep, but I can see it listed as a dep for LightInject.MVC and in the list of references in the project.
Are there any other steps I can take to manually configure the lifetime or otherwise verify that this method is available before Enabling MVC?
The issue here was that I installed LightInject.MVC with NuGet. It lists it's dependencies as:
LightInject.Web (>= 1.0.0.4)
LightInject (>= 3.0.1.7)
The after I exhausted this being an issue with versions of .Net 4.5 and possible issues with async. I decided to manually update both LightInject.Web and LightInject to their newest versions. After the update it resolved the issue.
I will add this as a bug in the listed dependencies on the projects site.
I am trying to install Ninject 3.3.2 in .NET Core, Released in May 2016. I got an error: The dependency Ninject 3.2.2 does not support framework .NETCoreApp, Version=v1.0.
Does anybody had similar problem, and is there any solution for this?
Ninject 3.3.0 was released September 26th 2017 and now targets .NET Standard 2.0 and thus also runs on .NET Core 2.0.
From the course of things (see issues/discussions on GitHub) it seems likely that some of the changes in the 4.0-beta will be reverted. I would not expected a 4.0 final shortly. Hence I would advise to go with the current version 3 release.
Just wanted to add; while both of the previous answers are correct in that ASP.Net core does provide built in dependency injection, it is NOT sufficient for more advanced scenarios. As it does not support a whole host of features that Ninject, AutoFac, Unity, or StructureMap supports.
At present, the only DI libraries that I am aware of that fully supports .net core are AutoFac and now Unity as well. It is very simple to add this in. The only thing you need to do to replace the built in DI is as follows. This example is for AutoFac but its almost identical for Unity it looks like.
First, replace the void on ConfigureServices in startup.cs with an IServiceProvider (dependency from AutoFac) like so:
public IServiceProvider ConfigureServices(IServiceCollection services)
Then create a container builder, build and resolve an IServiceProvider from ConfigureServices:
var builder = new ContainerBuilder();
builder.Populate(services);
var container = builder.Build();
return container.Resolve<IServiceProvider>();
I have a wrapper around the this second part that allows you to dynamically load and build different configurations using AutoFac modules, that I might be convinced to upload to GitHub or something if there is any interest.
Ninject does not support .NET Core. You can check it's website to be sure if there is no version that supports it.
ASP.NET Core has its own Dependency Injection container build in. See here.
Ninject does not support .Net Core, instead of this we can use dependency injection of .net core. following are the steps to implement.
Go to startup.cs at public void
ConfigureServices(IServiceCollection services)
Add services.AddTransient<Interface, Class>();
Go to the controller where you want to apply dependency injection.
Create a global private Interface _propertyName;
Pass the interface type variable to the constructor like
public Constructor(Interface name)
{
_propertyName= name;
}
Now you can access the members of the class through _propertyName.
I've got an MVC project and I've been doing DI in my WebAPI controllers for quite some time using a IHttpControllerActivator.
configuration.Services.Replace(
typeof(IHttpControllerActivator),
new UnityCompositionRoot(Container));
Now I need to use DI in an MVC controller so tried adding this line from the Unity.MVC project.
DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
But I'm getting an EntryPointNotFound exception when trying to set the resolver with the following stack trace.
at System.Web.Mvc.DependencyResolver.CacheDependencyResolver..ctor(IDependencyResolver resolver)
at System.Web.Mvc.DependencyResolver.InnerSetResolver(IDependencyResolver resolver)
at System.Web.Mvc.DependencyResolver.SetResolver(IDependencyResolver resolver)
at GRP2App.Web.App_Start.DependencyConfig.RegisterDependencys(HttpConfiguration configuration) in c:\Dev\SVN-Git\GRP2.5\GRP2App\GRP2App.Web\App_Start\DependencyConfig.cs:line 96
I've updated all my Unity nu-get packages so all the different projects should be on the same version. I'm not really sure what else to try.
I seem to remember this was an issue with upgrading from MVC 4 to MVC 5.
I upgraded using NuGet but there are several version numbers in the assembly redirects and razor engine sections of the web.config file which need updating.
This article contains full instructions with all the different places where the version numbers need upgrading.
http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2
This was the important part for me.
Update all elements that contain “System.Web.WebPages.Razor” from
version “2.0.0.0” to version“3.0.0.0”. If this section contains
“System.Web.WebPages”, update those elements from version “2.0.0.0”
to version“3.0.0.0”