Note that there are some explanatory texts on larger screens.

plurals
  1. POResolving dependencies in XAML using Autofac
    primarykey
    data
    text
    <p>I have a class <code>MyResource</code> in my application that looks like this:</p> <pre><code>public class MyResource : IMyResource { // ... whatever ... } </code></pre> <p>And when I initialize my application in App.xaml.cs I have something like that using Autofac:</p> <pre><code>builder.Register&lt;IMyResource&gt;(container =&gt; new MyResource()); </code></pre> <p>Now I need to add a <code>StaticResource</code> in a <code>Window</code> of my WPF application, something like this:</p> <pre><code>&lt;Window.Resources&gt; &lt;local:MyResource x:Key="MyResource" /&gt; &lt;/Window.Resources&gt; </code></pre> <p>But of course, the whole idea is <em>not to</em> reference a concrete instance of <code>MyResource</code> here. Moreover, I may need to use an instance of <code>MyResource</code> in different <code>Window</code>s or <code>UserControl</code>s across my application. So I would like to use an instance of <code>MyResource</code> as a <code>StaticResource</code> for my <code>Window</code> that is resolved through the Autofac container. How can I achieve this?</p> <p>I was thinking of adding the resource in the code-behind of my <code>Window</code>, but it may create a dependency on my container which I don't want.</p> <p>I was also thinking of doing something like that in App.xaml.cs, when I initialize the application:</p> <pre><code>App.Current.MainWindow.Resources.Add("MyResource", container.Resolve&lt;IMyResource&gt;()); </code></pre> <p>But when I use the resource in my XAML</p> <pre><code>&lt;ListBox ItemsSource="{Binding Source={StaticResource ResourceKey=MyResource}}"/&gt; </code></pre> <p>I get an <code>XAMLParseException</code> which inner exception's message stating that the resource named MyResource cannot be found. And even if it was working, I feel like it's a bit smelly.</p> <p>So how can this be achieved? Is it only possible? If not what are the best way to implement this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload