When will the Structuremap.MVC5 nuget package be updated to support Structuremap 4.x? - asp.net-mvc-5

If you have the StructureMap.MVC5 nuget package installed, and update the structuremap nuget package, the ControllerConvention class will require you to implement the ScanTypes method (from an updated IRegistrationConvention interface). This is the method signature:
public void ScanTypes(TypeSet types, Registry registry)
So my question is,
will there be an updated release to the StructureMap.MVC5 nuget package?
how should I implement the method?
Thanks.

Based on Charles Duffy's response, I went searching and found an answer:
https://github.com/webadvanced/Structuremap.MVC5/issues/15
public void ScanTypes(TypeSet types, Registry registry)
{
types.AllTypes().ForEach(type =>
{
if (type.CanBeCastTo<Controller>() && !type.IsAbstract)
{
registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
}
});
}
The poster (and I) is "not sure if this is the best way to go".

It doesn't appear as if the Structuremap.MVC5 package will be updated to support Structuremap 4.x directly.
However a relatively minor change will get it working.
#mnwsmitgave a good implementation explanation here - https://stackoverflow.com/a/35913874/1019768

Related

Azure function: Could not load file or assembly Microsoft.IdentityModel.Tokens, Version=5.2.1.0

Im writing an azure function to generate a JWT token and return it to the client. The code is tested locally in a console app and all seems to work fine. This is the package reference included in the working console app, and in my functions app:
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.2.1" />
When running the function host locally with func host start and executing the code it results in the error:
Could not load file or assembly 'Microsoft.IdentityModel.Tokens, Version=5.2.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'."
I don't understand why this is happening, the dll is laying in the output folder along with my application dll. The only other thing I can think of is that the function host has its own set of packages that it sources from and this one is not available yet, having been only released 12 days ago.
I'm not sure. Any help on why this is happening or how to get around it?
Details:
Azure Functions Core Tools (2.0.1-beta.22)
Function Runtime Version: 2.0.11415.0
I got this issue and it seems to be related to some kind of bug in the Azure function SDK. the fix was to add:
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
to your csproj file. As documented here
I had installed this package Microsoft.AspNetCore.Authentication.JwtBearer
And for me, the issue was resolved.
You can uninstall System.IdentityModel.Tokens.Jwt
Because the Microsoft package depends on the system package, so it gets installed automatically.
I was able to solve this exact issue by using an older version of the nuget package. My starting point was that I had copied a class file from an old project to a new one. The class file referenced JwtSecurityToken. This did not compile in the new project, so I added Security.IdentityModel.Tokens.Jwt from nuget package manager. I just added latest version. This worked fine locally, but just like you, it failed when published to azure. I then looked at the old project and noticed that it was using 5.1.4 of that Security.IdentityModel.Tokens.Jwt. So, I downgraded to that version and it now works when published.
fwiw: this is the v2 preview runtime version at the time I did this.
https://<mysite>.azurewebsites.net/admin/host/status?code=<myadminkey>
{
"id": "<mysite>",
"state": "Running",
"version": "2.0.11587.0",
"versionDetails": "2.0.11587.0-beta1 Commit hash: 1e9e7a8dc8a68a3eff63ee8604926a8d3d1902d6"
}
tl;dr
None of the above worked for me and this would randomly happen from time to time until today it happened all the time. The only reason I could see was that Microsoft.IdentityModel.Tokens was not directly referenced in the executing project, but was on a referenced project. The library was sitting in the bin folder, it just wouldn't load.
Reference
Taking a clue from this solution to another problem I was able to resolve it like so:
Solution
Create a static constructor in the app's entry point class
static MainClass()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
Add the handler
private static System.Reflection.Assembly? CurrentDomain_AssemblyResolve(object? sender, ResolveEventArgs args)
{
var domain = sender as AppDomain;
var assemblies = domain.GetAssemblies();
foreach(var assembly in assemblies)
{
if (assembly.FullName.IsEqualTo(args.Name))
{
return assembly;
}
}
var folder = AppDomain.CurrentDomain.BaseDirectory;
var name = args.GetLibraryName().Name.Split(Symbols.Comma).FirstOrDefault();
var library = $"{name}.dll";
var file = Path.Combine(folder, library);
if (File.Exists(file))
{
return Assembly.LoadFrom(file);
}
return null;
}

Autofac Dependency Injection in Azure Function

I am trying to implement DI using Autofac IOC in Azure function.
I need to build the container, but not sure where to put the code to build the container
I did write a blog entry for doing dependency injection with Autofac in Azure Functions. Have a look here:
Azure Function Dependency Injection with AutoFac: Autofac on Functions
It follows a similar approach like the one by Boris Wilhelms.
Another implementation based on Boris' approach can be found on github: autofac dependency injection
-- update ---
With Azure Function v2 it is possible to create nuget packages based on .net standard. Have a look onto
Azure Functions Dependency Injection with Autofac: Autofac on Functions nuget Package
I think for now you would need to do something ugly like:
public static string MyAwesomeFunction(string message)
{
if (MyService == null)
{
var instantiator = Initialize();
MyService = instantiator.Resolve<IService>();
}
return MyService.Hello(message);
}
private static IService MyService = null;
private static IContainer Initialize()
{
// Do your IoC magic here
}
While Azure Functions does not support DI out of the box, it is possible to add this via the new Extension API. You can register the container using an IExtensionConfigProvider implementation. You can find a full example DI solution in Azure here https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/.
Azure Functions doesn't support dependency injection yet. Follow this issue for the feature request
https://github.com/Azure/Azure-Functions/issues/299
I've written a different answer to the main question, with a different solution, totally tied to the main question.
Previous solutions were either manually initializing a DI or using the decorator way of doing it. My idea was to tie the DI to the Functions Builder in the same way we do with aspnet, without decorators.
I don't know why my post got deleted by #MartinPieters, it seems that it was not even read.
I found no way to officially disagree with that decision, so I kindly ask that the moderator read my answer again and undelete it.
You can do it using a custom [inject] attribute. See example here https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/

Precompiled Azure Function Behaving Unexpectedly

MyLibrary.dll
public class Person
{
[JsonProperty("name")]
public string Name { get; set; }
public static async Task Save(Person person)
{
DocumentClient client = CreateDocumentClient();
await client.OpenAsync();
await client.CreateDocumentAsync(CreateDocumentCollectionUri(), person);
}
}
MyFunctionApp.dll
public class SimpleHttpTrigger
{
public static async Task Run(HttpRequestMessage req)
{
Person bob = new Person() { Name = "Bob" };
await Person.Save(bob);
}
}
MyLibrary depends on:
Newtonsoft.Json 10.0.2
Microsoft.Azure.Documents.Client 1.13.1
And MyFunctionApp depends on MyLibrary.
The issue observed in this example is that the JsonProperty attribute is ignored when SimpleHttpTrigger.Run is called by the Azure Function CLI. SimpleHttpTrigger behaves as expected when called directly from a console app.
The issue can be resolved by changing MyLibrary's dependencies to match the versions currently used by the Azure Functions CLI:
Newtonsoft.Json 9.0.1
Microsoft.Azure.Documents.Client 1.11.4
It appears that Azure Function CLI ignores libraries in MyFunctionApp/bin when it has its own version of the library (found in node_modules/azure-functions-cli/bin). In this small example it's fine to match the dependencies but it isn't feasible when MyFunctionApp has a much larger dependency.
Is my understanding of this behaviour correct?
Is there any way to specify which version of these libraries to use in precompiled functions? I believe that one could get this behaviour in scripted functions by putting the dependencies inside the function's bin folder.
Update
My assumptions about the cause of this behaviour appear to be incorrect.
The newer versions of the Newtonsoft.Json and Microsoft.Azure.Documents.Client assemblies are in fact loaded alongside the Azure Function CLI's automatically loaded assemblies.
Which makes me even more confused as SimpleHttpTrigger.Run still behaves differently when called directly from a console app than it does when called by the Azure function host.
Any ideas what's going on? Possibly something stupid on my part.
Update 2
It looks like two different versions of the Newtonsoft.Json are used, whichever way the assemblies are loaded:
MyLibrary uses Newtonsoft.Json 10.0.2 as intended, but its dependency, Microsoft.Azure.Documents.Client 1.13.1, uses Newtonsoft.Json 9.0.1
Which might explain the incompatibility of the JsonProperty attribute.
Possibly? Please help, I'm very confused!
Basically, you are correct about the diagnosis of the problem.
This is an open issue with Azure Functions.
I stumbled on this myself and sympathize with your frustration.
Until the issue is solved, you must use the same major version of all the dependencies you happen to share with the implementation of Azure Functions.
Here is the list of Azure Functions dependencies : https://github.com/Azure/azure-webjobs-sdk-script/blob/dev/src/WebJobs.Script/packages.config
Open issues to track:
https://github.com/Azure/azure-webjobs-sdk-script/issues/573
https://github.com/Azure/azure-webjobs-sdk-script/issues/1311

ServiceStack IAutoQuery namespace could not be found?

I'm playing around with ServiceStack's AutoQuery, but getting stuck with this. I've put Plugins.Add(new AutoQueryFeature { MaxLimit = 100}); up, and tried to add all the namespaces, but no luck so far. Thanks.
UPDATE: I'm following the main, ServiceInterface, ServiceModel structure. When I put public IAutoQuery AutoQuery { get; set; } into main, it could be recognized. But not working in ServiceInterface. How to solve this?
All the AutoQuery functionality is contained in the single AutoQueryFeature.cs which is in the ServiceStack namespace.
This is also where you'll find the IAutoQuery interface (also in the ServiceStack namespace). This means if you can find AutoQueryFeature you'll also be able to find IAutoQuery by default, if you're having build errors, it's likely there's some other issue, i.e. try a clean build otherwise you maybe you need to restart Visual Studio.
The AutoQuery feature is in the ServiceStack.Server NuGet package:
PM> Install-Package ServiceStack.Server

Where is IRepository Defined - ServiceStack

I'm trying to figure out where IRepository interface lies and is defined:
public IRepository Repository { get; set; }
in this code here:
https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/RedisStackOverflow/RedisStackOverflow.ServiceInterface/AnswersService.cs
so is this IRepository part of the ServiceStack framework and ServiceStack's built-in IoC is injecting using this? I just want to know where to go find more about where this code is originating from.
I looked at the Redis ServiceModel but so is this Repository interface from the ServiceStack framework somewhere? I'm trying to understand more of the ORM part of Service stack and not sure if that's where this is coming from or what...
That interface is just part of the redis example project. The source can be found here. When trying to hunt down something like this look at the namespaces that are imported:
using RedisStackOverflow.ServiceModel;
using ServiceStack.ServiceInterface;
We know that if we are referencing IRepository in the code it must either be in the curernt namespace or one of those two.

Resources