RegisterType from unity configuration file - unity-container

I am migrating from Prism 4 to Prism 7.1, I cannot seem to find the ConfigureContainer method has been removed from the latest Prism release. In the past, I had used this method to load the unity configuration from the file system.
with the latest version of the Prism library, this appears not to be possible.
I have already explored the option of ModuleConfiguration, which to me does not provide the ability to inject dependencies through a configuration file in the same way.
Is there an alternate approach for this, where I can provide type registration through a configuration file.
Here is how I did it in the past:
1- In the BootStrapper following method was overridden:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
UnityConfigurationSection section = (UnityConfigurationSection)config.GetSection("unity");
if (section != null)
{
section.Configure(Container);
}
}
2- Add config section in the app.config file:
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
3- Add a unity config file which looks like:
<unity xmlns="schemas.microsoft.com/practices/2010/unity">
<sectionExtension type="Unity.FactoryConfig.FactoryConfigExtension, Unity.FactoryConfig"/>
<alias alias="Singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
<alias alias="ConfigFactory" type="Vms.Pt.Common.DependencyInjection.ComponentBuilder.ConfigClassFactory`1, Vms.Pt.Common.DependencyInjection.ComponentBuilder"/>
<container>
<!--Modal/popup provider service-->
<register type="IPopupService, GUI.Infrastructure"
mapTo="Services.PopupService, GUI.Infrastructure">
<lifetime type="Singleton"/>
</register>
</container>
</unity>

It's now called RegisterTypes in the PrismApplicationBase. Just override that and do whatever you would have done in ConfigureContainer.
Hint: if you don't like the "abstraction" Prism 7 put between you and IUnityContainer, you can call GetContainer() on the IContainerRegistry (it's an extension method) to get the hidden IUnityContainer instance.

Thanks Haukinger. I had to downgrade the Unity.Abstractions nugget to V3.31 to make the configuration work with prism 7. It does not work with the latest version of the Nugget.

Related

PaxExam tests configured with wrappedBundle()

For the configuration in PaxExam (version 4) we're using wrappedBundle() as you can see here:
wrappedBundle(mavenBundle().groupId("com.github.tomakehurst").artifactId("wiremock-jre8").versionAsInProject()),
Because we want to create an OSGi bundle out of an ordinary jar.
Then in order the wrap mechanism can be used we have to install the wrap feature:
features(karafStandardRepo, "wrap"),
The problem is when it comes to install wrappedBundle() the wrap feature is not yet there. How can I assure in the PaxExam configuration wrappedBundle() is executed only after the wrap feature is there and ready for use? The Karaf distribution we are using in this test is version 4.0.7.
Thanks for help,
Kladderradatsch
Yes, indeed we had to wrap the WireMock bundle generation by the PaxUrl Wrap mechanism into a separate feature file:
<features name="wiremock-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
<feature name="wiremock" version="${project.version}">
<feature prerequisite="true">wrap</feature>
<bundle>
wrap:mvn:com.github.tomakehurst/wiremock-jre8-standalone/2.21.0$Bundle-ClassPath=.
</bundle>
</feature>
</features>
Very important is here to configure the XML namespace properly, namely to address version v1.4.0 otherwise prerequisite is of no use. A further pitfall I stepped in before was not taking the standalone version of WireMock.
Then in the PaxExam configuration I have just installed the feature:
features(maven().groupId("com.company.wiremock").artifactId("wiremock-feature").type("xml").classifier("features").version("1.0.0-SNAPSHOT"), "wiremock"),
When it comes to initialize the WireMockServer in your tests, in order the resources in the new generated WireMock-Bundle can be loaded via ClassLoader.getResource() (internal stuff of that library), you have to do this here in your test otherwise the Bundle-Classloader of that WireMock-Bundle is not used:
#BeforeClass
public static void setup() {
ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(WireMockClassRule.class.getClassLoader());
wireMockServer = new WireMockServer(options().dynamicPort());
wireMockServer.start();
} finally {
Thread.currentThread().setContextClassLoader(savedClassLoader);
}
}
#AfterClass
public static void end() {
wireMockServer.stop();
}
You could put this in a JUnit #ClassRule for encapsulation.

How do I add Thymeleaf SpringSecurityDialect to spring boot

In the configuration of my template engine I would like to add SpringSecurityDialect() like:
#Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(new SpringSecurityDialect());
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
However eclipse is telling me:
The type org.thymeleaf.dialect.IExpressionEnhancingDialect cannot be resolved. It is indirectly referenced from required .class files
What does this mean and how can I fix it?
In pom.xml I have:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
As #Lachezar already answered, you have to add those missing dependencies. But the specified version with ext['thymeleaf.version'] = '3.0.0.RELEASE should be the same as in the compile dependencies so you better use ext['thymeleaf.version'] = '3.0.1.RELEASE'.
Furthermore, please note that it is enough to just specify a bean for the security dialect without providing a bean for the template engine. With Thymeleaf on the classpath, it will automatically recognize that the bean is an instance of IDialect and adds it directly to the dialects:
#Bean
public SpringSecurityDialect springSecurityDialect() {
return new SpringSecurityDialect();
}
It means that org.thymeleaf.extras:thymeleaf-extras-springsecurity4 has a dependency to org.thymeleaf:thymeleaf as you can see in the link to the repo above. Apparently you haven't provided this dependency. The class IExpressionEnhancingDialect is there. You can resolve that by adding the dependency to your project.
Since this may get a bit complicated... I'm also playing around with Spring Boot, spring security and the security dialect for thymeleaf (plus spring data with h2). Here are my gradle dependencies for reference, they may help you somehow:
ext['thymeleaf.version'] = '3.0.1.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.0.0'
dependencies {
compile("org.springframework.boot:spring-boot-devtools")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.1.RELEASE")
compile("com.h2database:h2")
}
Note that I want to use thymeleaf 3 instead of 2, that is why there are some extra unpleasant tweaks in my configuration.
EDIT: The version of thymeleaf-extras-springsecurity4 should be the same as thymeleaf.version as suggested in the other answer.

InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly

After deploying ASP.NET Core app to azure and opening the site, I get the following error:
InvalidOperationException: Could not find 'UserSecretsIdAttribute' on
assembly '******, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'.
The exception details also include that the error happens at Startup.cs on this line of code:
builder.AddUserSecrets();
Thank you
There was an update to the user secrets module just recently. Version 1.0.1 and up now requires you specify an assembly-level attribute for the id of the user secrets, or as a fallback, the way it was previously in project.json.
Here is the announcement on GitHub: https://github.com/aspnet/Announcements/issues/209
You can define the secrets id in the .csproj like this:
<PropertyGroup>
<UserSecretsId>aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed</UserSecretsId>
</PropertyGroup>
This generates the following assembly-level attribute. Alternatively, instead of adding it in the .csproj file, you can of course add it yourself e.g. to Startup.cs:
[assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")]
Also, you should use:
builder.AddUserSecrets<Startup>();
It will search for that attribute in the assembly of the given type, in this case I used the Startup class.
Note: this will be deprecated in 2.0: (1.0.2 and 1.1.1 have marked it obsolete)
builder.AddUserSecrets();
I checked the source code for the user secrets configuration, and calling AddUserSecrets() without the type does this:
var attribute = entryAssembly.GetCustomAttribute<UserSecretsIdAttribute>();
if (attribute != null)
{
return AddUserSecrets(configuration, attribute.UserSecretsId);
}
// try fallback to project.json for legacy support
try
{
var fileProvider = configuration.GetFileProvider();
return AddSecretsFile(configuration, PathHelper.GetSecretsPath(fileProvider));
}
catch
{ }
// Show the error about missing UserSecretIdAttribute instead an error about missing
// project.json as PJ is going away.
throw MissingAttributeException(entryAssembly);
It's trying to find the UserSecretsId attribute on your assembly, and failing that, checking if it could find it in project.json. Then (as commented) returns an error about the missing attribute as they wouldn't want to complain about project.json anymore as it is being deprecated.
I want to add to this answer, for those in my situation.
I am writing a .NET Core console app, trying to use the secrets manager (not sure it's meant for console apps). The only way I was able to rid myself of the error was using the assembly level attribute on the assembly where I was using the secrets manager.
As I said, I am not sure if the secrets manager is meant for console apps. So maybe there is an issue with .xproj files vs. .csproj files.
My .NET Core 3.1 Worker Service required additional setup (more than a Web project).
In Program.cs in the CreateHostBuilder method I needed this:
.ConfigureAppConfiguration((ctx, builder) =>
{
// enable secrets in development
if (ctx.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Worker>();
}
})
But (unlike my Web project) I explicitly needed to add this nuget package:
install-package Microsoft.Extensions.Configuration.UserSecrets
After that I could access secrets.

ReactJS.NET - Bundles - TinyIoCResolutionException: Unable to resolve type: React.IReactEnvironment

I'm attempting to minify my .JSX files with ASP.NET Minification and Optimization via System.Web.Optimization.React. I've installed the MVC4 React Package as well as the Optimization package, but whenever I try to include a bundle I get the following:
React.TinyIoC.TinyIoCResolutionException: Unable to resolve type: React.IReactEnvironment
The InnerException is always null
My bundles are setup as follows:
bundles.Add(new ScriptBundle("~/Bundle/Scripts/ReactJS").Include(
"~/Scripts/React/react-0.12.2.js",
"~/Scripts/React/react-with-addons-0.12.2.js",
"~/Scripts/React/JSXTransformer-0.12.2.js"
));
bundles.Add(new JsxBundle("~/Bundle/Scripts/ReactCalendar").Include(
"~/Scripts/React/Calendar/Main.react.jsx",
"~/Scripts/React/Calendar/Components/Calendar.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarEvent.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarControls.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarTimeSlots.react.jsx"
));
And included in the view as:
#section scripts{
#Scripts.Render("~/Bundle/Scripts/ReactJS");
#Scripts.Render("~/Bundle/Scripts/ReactCalendar");
}
The error is always thrown on line:
#Scripts.Render("~/Bundle/Scripts/ReactCalendar");
Anyone got any ideas on how to solve / debug this one? Let me know if more info is needed.
I'm not sure if this is the same issue I was facing, but I googled the exact same error, found this SO topic as the first hit, with no definitive answer, so I thought I'd offer my solution.
I'm using .NET 4.5 in an MVC app, and React.Web.Mvc4 v3.0.0.
I managed to work around this issue with the help of this comment on Github.
Here's my entire ReactConfig.cs:
using React;
using React.TinyIoC;
using React.Web.TinyIoC;
namespace NS.Project
{
public static class ReactConfig
{
public static void Configure()
{
Initializer.Initialize(AsPerRequestSingleton);
ReactSiteConfiguration.Configuration
.SetLoadBabel(false)
.AddScriptWithoutTransform("~/React/dist/server.bundle.js");
}
private static TinyIoCContainer.RegisterOptions AsPerRequestSingleton(
TinyIoCContainer.RegisterOptions registerOptions)
{
return TinyIoCContainer.RegisterOptions.ToCustomLifetimeManager(
registerOptions,
new HttpContextLifetimeProvider(),
"per request singleton"
);
}
}
}
Then, I'm callingReactConfig.Configure explicitly from Application_Start.
"Unable to resolve type: React.IReactEnvironment" with no InnerException generally means ReactJS.NET is not initialising properly for some reason. In web apps, ReactJS.NET handles initialisation through the use of WebActivator. Make sure your project is referencing React.Web, React.Web.Mvc4 and WebActivatorEx, and all the corresponding .dll files are ending up in your app's bin directory.
Also, you do not need to (and should not) include JSXTransformer in your JavaScript bundles, as ReactJS.NET does all the JSX compilation server-side.
Something looks like changed from React.Web.MVc4 version 4.0.0. versions before didnt have that problem.
as stated here
Install the React.Web.Mvc4 package through NuGet. You will also need to install a JS engine to use (either V8 or ChakraCore are recommended). See the JSEngineSwitcher docs for more information.
To use V8, add the following packages:
JavaScriptEngineSwitcher.V8
JavaScriptEngineSwitcher.V8.Native.win-x64
ReactConfig.cs will be automatically generated for you. Update it to register a JS engine and your JSX files:
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.V8;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(React.Sample.Mvc4.ReactConfig), "Configure")]
namespace React.Sample.Mvc4
{
public static class ReactConfig
{
public static void Configure()
{
ReactSiteConfiguration.Configuration
.AddScript("~/Content/Sample.jsx");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
}
}
}
If anyone needs this, just install this nuget and it will resolve this issue.
System.Web.Optimization.React

Export package in OSGi Bundle

I have an OSGi Bundle and a servlet. Now I want to access the bundle from the servlet. For that purpose I use the following in the servlet:
#Resource
BundleContext context
...
ServiceReference ref = context.getServiceReference("package.MyOSGiServiceInterface");
MyOSGiServiceInterface service = context.getService(ref);
The Problem is that my servlet doesn't know MyOSGiServiceInterface 'cause that is defined in the OSGiBundle. In Eclipse I added a reference to the bundle Project in my Build Path. But at runtime it obviously can't find it.
To solve that Problem I played around with
(in bundle manifest)
Export-Package: package-of-osgi-service-interface
(in servlet manifest)
Import-Package: package-of-osgi-service-Interface
Dependencies: ...,deployment.MyBundle
But I couldn't solve it.
Whats the missing step? How can I tell JBoss to add the package containing MyOSGiServiceInterface in OSGiBundle to the class path?
Thanks for answers!
(JBoss AS 7.1.1)
--> error message <--
Eventually I solved it. I had to put the right combination of settings together to reach my goal:
Deploy the bundle per: File - Export - "Deployable plug-ins and fragments" into folder: "jboss/standalone/deployments"
Bundle-Manifest:
Bundle-SymbolicName: TestBundle
Bundle-Version: 1.0.0
Export-Package: "package-which-includes-my-service"
Servlet-Manifest:
Dependencies: org.osgi.core,org.jboss.osgi.framework,deployment.TestBundle:1.0.0
Import-Package: "package-which-includes-my-service"

Resources