How do I specify what would normally be in web.config for an Azure Function? - azure

I'm creating an Azure Function, and I need to set this parameter what would normally go in the web.config file:
<entityFramework codeConfigurationType="xxxxxxxx">
But Azure Functions doesn't have a web.config. How do I configure stuff that isn't a simple key/value app setting?
The entity framework code is in a class library used by lots of other things, so I can't really use code based config without major hassle.

You can place it in your code. Microsoft documentation with all options is here: https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/code-based#moving-dbconfiguration
[DbConfigurationType(typeof(MyDbConfiguration))]
public class MyContextContext : DbContext
{
}
or
[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")]
public class MyContextContext : DbContext
{
}

Related

Azure App Configuration to strongly-typed configuration objects

I've been playing around a bit with Azure App Configuration.
Here's an example configruation:
var environmentVariable = Environment.GetEnvironmentVariable("AppConfigurationConnectionString");
var config =
new ConfigurationBuilder()
.AddAzureAppConfiguration(options =>
{
options.Connect(environmentVariable)
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
});
})
.Build();
services.AddSingleton<IConfiguration>(config);
Following this, I can inject an IConfiguration instance into my services and use _config["settingName"] to access config settings. This all works well and is really quite nice.
One thing that I don't know how to do is to map groups of related settings to a strongly typed object (that is, without having to do it all manually, which I could do, but... hoping there's a better way).
In conventional ASP.NET core configuration, I can group related settings settings as follows (i.e. in appsettings.json)
{
"test": {
"key1": "value1",
"key2": "value2"
}
}
using the IOptions pattern as follows:
services.Configure<Test>(config.GetSection("test"));
which allows me to inject a strongly-typed IOptions<Test> instance into my classes. IMO this is a bit nicer than a big flat indexer, where I use _config["key1"] to get config settings.
Is there an approach for Azure App Configruation to allow me to automatically configure strongly-typed config objects that can be injected into my classes?
TIA
.NET Core flattens objects in appsettings.json when it imports them into IConfiguration. For example, your test object becomes the following two keys in IConfiguration
_config["test:key1"]
_config["test:key2"]
This means that you can accomplish exactly what you want with Azure App Configuration by storing the settings in this flattened manner. The Azure App Configuration UI in the Azure portal has an import utility that will allow you to import an appsettings.json file and it does this importing for you.
Here is an example of the import utility in use:
After you have the flattened object in Azure App Configuration the exact code you have will work.

Application Initialization in Azure Function Project in VS2017 15.3.4?

In Visual Studio 2017 with the latest update, for azure functions template, I want something where I can initialize like program.cs in webjobs template.
I am trying to create a new subscription with new namespace Manager when application initializes so that I can listen to one service bus topic.
Is there a way to do that? If yes then how?
If you intend to create a subscription that this Function will be triggered on, there is no need to do that manually. Function App will create the subscription based on your binding at deployment time.
For other scenarios (e.g. timer-triggered function), you can do the initialization in a static constructor:
public static class MyFunction1
{
static MyFunction1()
{
var namespaceManager = NamespaceManager.CreateFromConnectionString(connString);
if (!namespaceManager.SubscriptionExists("topic1", "subscription1"))
{
namespaceManager.CreateSubscription("topic1", "subscription1");
}
}
[FunctionName("MyFunction1")]
public static void Run(
// ...
}
Static constructor will run at the time of the first function call.
for azure functions template, I want something where I can initialize like program.cs in webjobs template.
As far as I know, Azure functions do not have good support for this right now. You can find a similar question:
Question:
I have a C# function and want to know if there is any Initialization point. I have dependency injection containers that need initialization
and want to know where to do that.
Mathew's reply
We don't have a good story for this right now. Please see open issue
here in our repo where this is discussed.

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/

Servicestack - Grouping like services together

Was wondering if there's a recommended best-practice way of grouping similar services together in what's becoming a larger and larger project. Say that most of my services can be lumped in either dealing with "Pro" data or "Amateur" data (the data goes way beyond a simple flag in a table, the data itself is totally different, from different tables, on the pro or amateur side.
I know I can add routes to my classes...
/pro/service1
/am/service2
It looks like I can put the DTOs in namespaces....
What about the Service.Interface items (Service and Factory classes). Would you put those into namespaces also?
Finally, is there a way for the metadata page to reflect these groupings? I started to go down this road, but all the services listed out in alphabetical order, and you couldn't see the route or namespace differences between service1 and service2.
thank you
If you want, you can split multiple Service implementations across multiple dlls as described on the Modularizing Services wiki.
You can safely group service implementation classes into any nested folder groupings without having any impact to the external services. But changing the namespaces on DTO's can have an effect if your DTO's make use of object, interfaces or abstract classes which emit type info containing full namespaces.
In ServiceStack v4.09+ (now on MyGet) the MetadataFeature includes the ability to customize the ordering of the metadata page, e.g you can reverse the order of the metadata pages with:
var metadata = (MetadataFeature)Plugins.First(x => x is MetadataFeature);
metadata.IndexPageFilter = page => {
page.OperationNames.Sort((x,y) => y.CompareTo(x));
};
Organising your large project:
For a complex service(s) I setup 4 projects in one solution.
AppHost, This takes care of the configuration of the service. (References Model, Service and Types)
Model, This is the database model (Does not reference other projects)
Service, This is the implementation of the service only, not the interfaces or DTOs (References Model and Types)
Types, This includes my Interfaces, DTOs and routes. (Does not reference other projects)
Having a separate Types library allows the distribution to clients, for example for use with the ServiceStack JsonServiceClient.
Yes you can namespace the Interfaces, DTOs and factory classes, any way you want. They will work as long as they are referenced in your service correctly.
If you are trying to separate more than one service, you should consider separating your service code into logical folders within the Service project. i.e.
/Service/Pro
/Service/Amateur
Wrap the outer code of your Service methods in a public partial static class MyServiceStackApplication, with an appropriate name. Then reference this as the assembly in the AppHost constructor. So for example:
Pro Service (Service Project/Pro/UserActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Pro
{
public class UserActionsService : Service
{
public User Get(GetUserRequest request)
{
}
}
// ...
}
}
Pro Service (Service Project/Pro/OtherActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Pro
{
public class OtherActionsService : Service
{
public Other Get(GetOtherRequest request)
{
}
}
// ...
}
}
Amateur Service (Service Project/Am/UserActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Amateur
{
public class UserActionsService : Service
{
public User Get(GetUserRequest request)
{
}
}
// ...
}
}
etc.
You can see from the above code we can have multiple files, all separated out and organised, but one assembly for ServiceStack to reference in the AppHost:
public AppHost() : base("Pro & Amateur Services", typeof(MyServiceStackApplication).Assembly) {}
Using the reference to the MyServiceStackApplication assembly, and using the partial keyword allows you to organise the code into manageable groupings.
Metadata:
Unfortunately separating the metadata by namespace isn't supported. You could try and customize the MetaDataFeature yourself, but it does seem like a useful feature, being able to separate multiple services where they are hosted in the one ServiceStack application. I would suggest you raise a feature request.
Mythz is bringing out features faster than lightning. :) Seems like he has that covered in the next release and you should be able to apply a custom filter to HostContext.Metadata.OperationNamesMap.

Can I proxy a ServiceStack Service?

I'm wondering if it's possible to have ServiceStack use an AOP-proxied service, instead of the main implementation. I would like to avoid having the class that inherits from ServiceStack.ServiceInterface.Service simply be a wrapper, if possible. It looks to me like it will need to be, but I thought it wouldn't hurt to ask, to be sure.
I am looking for a way to achieve this, to proxy the services of a ServiceStack app.
Till now what I have learned is that: The only way we can generate a proxy to a service like
[Route("/reqstars")]
public class AllReqstars : IReturn<List<Reqstar>> { }
public class ReqstarsService : Service
{
public virtual List<Reqstar> Any(AllReqstars request)
{
return Db.Select<Reqstar>();
}
}
Is using a Custom Service Generation Strategy. And generating proxies of IService interface with class target and marking all the method of the service as virtual.
I have not tested this yet and even I do not know (and this is what I am researching for now) if ServiceStack can handle a service generator delegate so I can use Castle's DynamicProxy.
Good luck!

Resources