Posts

Showing posts with the label dependency-injection

How to catch an exception and respond with a status code in .NET Core

Image
Clash Royale CLAN TAG #URR8PPP How to catch an exception and respond with a status code in .NET Core I am running a .Net Core Web API project. I have a startup file (below). In the Startup.ConfigureServices(...) method, I add a factory method that creates an instance of IFoo. I want to catch any exceptions that the IFooFactory throws and return a better error message with a status code. At the moment I getting a 500 Error with the exception Message. Can anyone help? Startup.ConfigureServices(...) public interface IFooFactory { IFoo Create(); } public class FooFactory : IFooFactory { IFoo Create() { throw new Exception("Catch Me!"); } } public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddScoped<IFooFactory,FooFactory>(); services.AddScoped(serviceProvider => { IFooFactory fooFactory = serviceProvider.GetService<IFooFactory>(); return fooFacto...

In Unity, how do I inject a named dependency into a constructor with other dependencies?

Image
Clash Royale CLAN TAG #URR8PPP In Unity, how do I inject a named dependency into a constructor with other dependencies? I have a service with some dependencies but 1 of them is a named dependency. So, want to config my Unity container to inject that. I have some like this: Register of types in Unity container: container.RegisterType<IOtherService, Implementation>("SpecificImp); container.RegisterType<IOtherService, OtherImplementation>("otherImp"); container.RegisterType<IService, Service>( new InjectionConstructor( // Explicitly specify a constructor new ResolvedParameter<IOtherService>("SpecificImp") // Resolve parameter of type IRepository using name "Client" ) ); Service: puclic class Service : IService { private read-only IOtherService _otherService; private read-only IworkContext _workContext; public Service( IOtherService otherService, IworkContext workContex...