can you inject dependencies into postsharp attribute using structure map - structuremap

I use structure map for dependencies injection, I also now want to use postsharp for some authorisation checking at my service layer. because my service layer has all injected repositories is there a way I can inject or pass these repositories to the postsharp attribute to query the sql and provide authorisation?

I've never used PostSharp - does the code in the PostSharp attributes execute at runtime, or during a post-compile pre-runtime stage?
If the code executes at runtime, you should be able to do service location using a static gateway (ObjectFactory.GetInstance).

Related

ServiceStack: container.AutoWire(this) gives a NullReferenceException

If I in my AppHostBase descendant (web api project ) use container.AutoWire(this), it will result in a NullReferenceException in the ServiceStack code, if I am using a web project, thus starting it with the CreateHostBuilder(args).Build().Run(); in the main method.
The error is reproduced in this Github project: https://github.com/tedekeroth/ServiceStackAutoWireTest
The error occurs in AppHostBase.Netcore.Cs, line 158:
If I remove the container.AutoWire(this); in TestAppHost.cs, the error goes away, but then the dependency injection does not work, meaning the Logger in TestAppHostproperty is not assigned:
I am not sure why this happens or what I can do about it. I'd appreciate some input, thanks.
Setup
Visual Studio 2019
Target framework: .NET 5.0 (Console Application)
Project SDK: Microsoft.NET.Sdk.Web
ServiceStack 5.11.0
The IOC AutoWire API attempts to autowire all public property dependencies of an object which is definitely something you should never attempt to do with the AppHost which encapsulates the configuration and behavior of your ServiceStack App where indiscriminatingly overriding every public property is going to leave it in a corrupted state.
Registering your AppHost in the IOC shouldn't be necessary as it's available everywhere via the HostContext.AppHost singleton. It's also a bad idea trying to reference any type defined in your Host Project, (the AppHost being the canonical example) since it creates a circular reference to your Host project in your App logic dependencies which shouldn't have any references back to its Host project, your Host project is supposed to reference all your projects .dll's, configure your App's and all its dependencies, not the other way around.
Should you need access to any Plugins it's recommended to use the GetPlugin<T>() API in your Service for optional plugins or AssertPlugin<T>() for required plugins. If you need to resolve any deps manually you can use TryResolve<T>() API in your Service class. For any of your App's custom config I'd recommend registering them in a custom AppConfig class for your Services to access like any other dependencies.
Otherwise if you really need access to the AppHost you can use the HostContext.AppHost singleton. If you absolutely need to have the AppHost in the IOC, just register it as a normal singleton, i.e. don't try to autowire it:
container.Register<IAppHost>(c => this);
However as mentioned earlier I'd strongly advise against it, have everything your App needs in a custom class (e.g. AppConfig) that is accessed like a normal dependency.

In Azure Function which depends on .NET Standard library, how do I use ILogger log in a dependent .NET Standard Lib?

I have a Azure Function app (2.0) which depends on a .NET Standard Library contained within the same solution. I understand how to use the ILogger log within the azure function itself, but I want to use the same logger to log information within the .NET Standard library as well.
I want to avoid passing the log instance within the function to another class. I would prefer to use DI. How can I accomplish this?
For example, suppose I have a function app with a single function name FunctionName1. Suppose I have a dotnet standard 2.0 library named NetStandardLibrary1 with a class named MyClass1. Within the MyClass1, I have a single method named MyMethod1. I want to log information within MyMethod1 in the same way I would when I use ILogger log within FunctionName1.
You can set up Dependency Injection in Azure Functions. It's set up similarly to .net core a d you can use it to inject a logger.
See this post for details setting up DI.
https://ikethe.dev/azure-functions-adds-dependency-injection/

equivalent of ActivatorUtilities.CreateInstance in Autofac

Are there any equivalent for following method from Microsoft Dependency Injection in Autofac.
ActivatorUtilities.CreateInstance(serviceProvider)
There is no direct analog for ActivatorUtilities in Autofac. But you have options.
You can directly resolve things that are registered (service location) - lifetimeScope.Resolve<T>()
If you need to resolve any type at all rather than only things you've registered, AnyConcreteTypeNotAlreadyRegisteredSource can help.
You can inject properties into constructed objects - lifetimeScope.InjectProperties(obj)
Or, if you really need ActivatorUtilities, you can use the Autofac.Extensions.DependencyInjection package to create a Microsoft container backed by Autofac and use the utility methods directly.

How to (not) specify scope in class libraries with Ninject3

I've an ASP.NET MVC application using Ninject3 (NuGet install). The solution contains:
an MVC project (composition root);
a Domain Model project;
a Data Layer project;
a scheduler project (running scheduled jobs within a windows service and holding an alternative composition root);
some other projects.
I'm following the approach to have many small modules spread across the projects defining the bindings. The two composition roots use exactly the same bindings.
I cannot figure out how to configure scope for the modules within the class libraries. For example, given these bindings:
Bind<IDomainService1>()
.To<Service1Impl>()
.InSingletonScope(); //This should always be a singleton
Bind<IDomainService2>()
.To<Service2Impl>(); //No scope specified
I would always want a single instance of Service1Impl, whereas scope for Service2Impl should depend on the composition root used. MVC project should have InRequestScope() for Service2Impl (and for all other bindings with unspecified scope). Scheduler project, which does not run within an http context, should use InThreadScope().
Is this approach correct? If yes, what is the right way of configuring this behaviour?
In Ninject, not specifying the scope means InTransientScope().
Your choices are to either duplicate the bindings or create a custom InScope() scoping rule for the binding.
The cleanest solution (especially given that MVC is already in play) is for you to create a plugin that slots into the InRequestScope() mechanism.
There is a CreateScope() method which currently has minimal documentation in the ninject.extensions.namedscope README, which is used like this. It requires you to select 'Include Prerelease' in NuGet. (And I should be writing a wiki article on it but I have too many other things on my plate...)

How should I use ninject in a multiproject mvc app?

My app is set up this way
Web
Data
Services
POCO Entities
Controllers use services (so they should be injected)
Services use Repositories (which I assume should also be injected)
I have this already set up so that the Controllers receive the service they need through Ninject but I not sure how to get this done with the services =>repositories
any help with this?
You could use the ninject.web.mvc extension. It contains a sample application which illustrates how you could register the container in Global.asax.
Bob has several blogs about repository pattern with Ninject and NHibernate. It's pretty much the same for all other OR Mappers:
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/
http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/
Simply set up your services' dependencies as well as the controller's dependencies. Ninject will walk the dependency chain and resolve all of them.
for example,
ProductController has dependency on IProductService
IProductService is implemented with ProductService that has a dependency on IProductRepository
IProductRepository is implemented with NHibernateProductRepository that has a dependency on ISession.
when your NinjectControllerFactory attempts to resolve ProductController, it sees the dependency on IProductService. it resolves that dependency as ProductService, and sees that it has a dependency on IProductRepository. and it will continue on down the chain until it can resolve completely an argument.
so the important part is to Bind ANY dependencies, not just those in a Controller.

Resources