i am using mef with prism. i can use mef because i like the export, import, metadata attributes and mostly aggregate cagalog usage. so i want to use mef with prism project.
In my plan, my solution projects must be use autofac or castle windsor ioc container and i implement like that except prism project(wpf). In case, i am not prefer to use autofac or castle windsor instead of mef's default di/ioc but too many alternative usage of personal experimantals are failed.
Is there a any stable sample project i can use? I want to change only ioc of mef with all mef functionalty.
My classic mef bootstrapper code is bellow
Imports System.ComponentModel.Composition.Hosting
Imports Microsoft.Practices.Prism.MefExtensions
Imports Microsoft.Practices.ServiceLocation
Public Class Bootstrapper2
Inherits MefBootstrapper
Protected Overrides Sub ConfigureContainer()
MyBase.ConfigureContainer()
Dim ag As New AggregateCatalog()
ag.Catalogs.Add(New AssemblyCatalog(GetType(Bootstrapper2).Assembly))
ag.Catalogs.Add(New DirectoryCatalog("..\..\modules\", "Prism.Sample.Modules.*.dll"))
Me.AggregateCatalog.Catalogs.Add(ag)
End Sub
Protected Overrides Function CreateShell() As DependencyObject
Dim s As Shell = ServiceLocator.Current.GetInstance(Of Shell)()
Return s
End Function
Protected Overrides Sub InitializeShell()
Application.Current.MainWindow = Shell()
Application.Current.MainWindow.Show()
End Sub
End Class
Shell's code is bellow:
Imports System.ComponentModel.Composition
<Export()> _
Public Class Shell
Sub New()
InitializeComponent()
End Sub
<Import(AllowRecomposition:=False)> _
Public Property ViewModel() As ShellViewModel
Get
Return CType(Me.DataContext, ShellViewModel)
End Get
Set(value As ShellViewModel)
Me.DataContext = value
End Set
End Property
End Class
Now, everythings working like an expected.
modified/overrided bootstrapper's ConfigureServiceLocator() method is bellow.
Private autofacBuilder As New Autofac.ContainerBuilder
Protected Overrides Sub ConfigureServiceLocator()
Dim autofacContainer = autofacBuilder.Build()
Dim autofacSL = New Prism.AutofacExtension.AutofacServiceLocatorAdapter(autofacContainer)
ServiceLocator.SetLocatorProvider(Function() autofacSL)
End Sub
then i have got an too many resolving exception for example:
exception message:
Activation error occured while trying to get instance of type RegionAdapterMappings, key "".
Prism or another code base trying to resolve IRegionAdapterMappings from the servicelocator but currentservice locator not knowns what is this.Because mef is allready registered this types((ConfigureContainer) before CreateServiceLocator.
So, then i trying to add mef's aggregate catalog to register autofac container with Autofac.Integration.Mef project like this:
Private autofacBuilder As New Autofac.ContainerBuilder
Protected Overrides Sub ConfigureServiceLocator()
autofacBuilder.RegisterComposablePartCatalog(Me.AggregateCatalog)
Dim autofacContainer = autofacBuilder.Build()
Dim autofacSL = New Prism.AutofacExtension.AutofacServiceLocatorAdapter(autofacContainer)
ServiceLocator.SetLocatorProvider(Function() autofacSL)
End Sub
Then i have got a diffrent exception: IServiceLocator not registered etc...
I have not a complately solutions for changing mef's ioc container because its own container types and uses her own extensibility. Tried to use Autofac.Integration.Mef but maybe it not future compatible. maybe not developep when mef' new releases.
I am a big blakc hole i think. Is there a any way can't i see?
Thanks.
Related
I have inherited an a VB.NET WinForms application. It is very poorly written with a lot of bad practices. The first order of business is to get some DI into the app with a container to resolve the dependencies so I can start breaking this thing up and getting it under test.
This is my first WinForms app and I am learning the nuances of a non-request based application on a single thread.
I am using Simple Injector as the IoC container.
One of my use cases that I need to refactor is a UserControl that is extending a DevExpress XtraUserControl.
From the Simple Injector docs:
Note: It is not possible to use Constructor Injection in User Controls. User Controls are required to have a default constructor. Instead, pass on dependencies to your User Controls using Method Injection.
I am following the docs verbatim on how to set up property injection:
IPropertySelectionBehavior
Here is my configuration:
Private Shared Sub Bootstrap()
Container = New Container()
Container.Options.DefaultScopedLifestyle = New ThreadScopedLifestyle()
Container.Options.PropertySelectionBehavior = New ImportPropertySelectionBehavior()
Container.Register(Of ICommissionManager, CommissionManager)(Lifestyle.Singleton)
Container.Register(Of frmMain, frmMain)(Lifestyle.Singleton)
Container.Register(Of viewSalesCustomers, viewSalesCustomers)(Lifestyle.Transient)
'https://stackoverflow.com/questions/38417654/winforms-how-to-register-forms-with-ioc-container/38421425
Dim registration As Registration = Container.GetRegistration(GetType(viewSalesCustomers)).Registration
registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent, "a reason")
Container.Verify()
End Sub
The user control:
Public Class viewSalesCustomers
Inherits DevExpress.XtraEditors.XtraUserControl
<Import>
Public Property CommissionManager As ICommissionManager
...redacted...
Private Sub viewSalesCustomers_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim commissions As ICollection(Of Commission)
commissions = CommissionManager.Get(Function(commission) commission.CommissionId = 1) <-- Always nothing (null)
End Sub
I know the container is resolving for anything deriving from Form (I tested it through constructor injection).
Not sure what I missing here on the property injection for this control.
UPDATE:
#Steven was spot on. I found where they are instantiating the control.
Private Sub BarSubItem2_ItemClick(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarSubItem2.ItemClick
Cursor = Cursors.WaitCursor
'Dim mView as New viewSalesCustomers()
Dim mView As viewSalesCustomers
mView = Program.Container.GetInstance(Of viewSalesCustomers)
showViewer(mView, "viewSalesCustomers")
Cursor = Cursors.Default
End Sub
I have a winforms applications that has an ms sql server backend. In my database i have lookup tables for like status, and other tables where the data rarely changes. In my application, several forms might use the same lookup tables (Some have a lot of data in them). Instead of loading/filling the data each time the form is open, is there a way to cache the data from the database that can be accessed from multiple forms. I did some searching, but couldnt find the best solution. There is caching, dictionaries, etc. What is the best solution and can you point me to the documentation that discusses it and may even have an example.
Edit:
In my original post I failed to mention that I have a strongly typed dataset and use tableadapters. I want to preload my lookup tables when my application starts, and then have these dataset tables be used throughout the application, on multiple forms without having to fill them on every form.
I have tried creating a class:
Public Class dsglobal
Public Shared EML_StaffingDataSet As EML_StaffingDataSet
Public Shared Sub populateDS()
EML_StaffingDataSet = New EML_StaffingDataSet
End Sub
Public Shared Sub loadskills()
Dim ta As New EML_StaffingDataSetTableAdapters.TSTAFFSKILLTableAdapter
ta.Fill(EML_StaffingDataSet.TSTAFFSKILL)
End Sub
End Class
I run this on a background worker when my application is starting up. So it loads the dataset table. On fill, I can see the datatable has data in it. When I open a form, i want to use the dataset table, but it seems to clear the data out. Not sure if my approach is correct or where my error is.
Edit2:
I have also tried this per comments, but not sure I am doing it correctly. If I am doing it correctly, then how do I use that as a datasource at design time, can i only do that programmatically?
Public Module lookupdata
Private EML_StaffingDataSet As EML_StaffingDataSet
Private skillvalues As List(Of skill)
Public ReadOnly Property skill As List(Of skill)
Get
If skillvalues Is Nothing Then
getskillvalues()
End If
Return skillvalues
End Get
End Property
Private Sub getskillvalues()
skillvalues = New List(Of skill)
EML_StaffingDataSet = New EML_StaffingDataSet
Dim ta As New EML_StaffingDataSetTableAdapters.TSTAFFSKILLTableAdapter
ta.Fill(EML_StaffingDataSet.TSTAFFSKILL)
For Each row As DataRow In EML_StaffingDataSet.TSTAFFSKILL
Dim skill As New skill
skill.skill_id = row("skill_id")
skill.skill_desc = row("skill_desc")
skill.skill_open_ind = row("skill_open_ind")
skillvalues.Add(skill)
Next
End Sub
End Module
Public Class skill
Public Property skill_id As Integer
Public Property skill_desc As String
Public Property skill_open_ind As Boolean
End Class
You might want to consider a lazy loading pattern, like this:
Public Module LookupData
Private statusValues As List(Of LookupValue)
Public Readonly Property Statuses As List(Of LookupValue)
Get
If statusValues Is Nothing Then
GetStatusValues()
End If
Return statusValues
End Get
End Property
Private Sub GetStatusValues()
statusValues = New List(Of LookupValue)
Dim sql = "select key, value from StatusTable"
'TODO: Read the items from the database here, adding them to the list.
End Sub
End Module
Public Class LookupValue
Public Property Key As String
Public Property Value As String
End Class
The idea is that you've got a single instance of LookupData (a Module in VB, there can be only one). Lookup data has a series of Properties, each of which returns a list of values from the database. If the data has already been loaded, it just returns what it has cached. If the data has not been loaded, then the first time it is referenced it retrieves it from the database.
You can consume it elsewhere in your code as follows:
Dim myStatuses = LookupData.Statuses
I'm trying to access Label from another class's method running in background thread with the help of MainWindow Class's Public Shared Sub like this:
Private Delegate Sub ProgressReportInvoker(ByVal progressStr As String)
Public Shared Sub ProgressReport(ByVal progressStr As String)
If MainWindow.Label.Dispatcher.CheckAccess() Then
MainWindow.Label.Content = progressStr
Else
MainWindow.Label.Dispatcher.Invoke(
New ProgressReportInvoker(AddressOf ProgressReport),
progressStr)
End If
End Sub
Call from another class is below:
MainWindow.ProgressReport("Sample text")
But I have this error on "MainWindow.Label":
Reference to a non-shared member requires an object reference.
I noticed that if I declare Label in MainWindow.g.i.vb as Public Shared than error is gone:
#ExternalSource ("..\..\MainWindow.xaml", 11)
<System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")>
Public Shared WithEvents Label As System.Windows.Controls.Label
#End ExternalSource
But this file is generated automatically from the *.XAML file so it takes previous look when I compile the code.
Is there any way to make control shared in *.XAML file or may be there are any alternatives of making my task possible?
You should access the instance of the MainWindow and not the type itself:
Public Shared Sub ProgressReport(ByVal progressStr As String)
Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
If mainWindow.Label.Dispatcher.CheckAccess() Then
mainWindow.Label.Content = progressStr
Else
mainWindow.Label.Dispatcher.Invoke(
New ProgressReportInvoker(AddressOf ProgressReport),
progressStr)
End If
End Sub
I tried this before but problem is in multitasking. I can't access the form from another thread without some special moves which I don't know about
You can only access a UI control in the thread on which it was originally created:
Application.Current.Dispatcher.BeginInvoke(New Action(Sub()
Dim mainWindow = Application.Current.Windows.OfType(Of MainWindow).FirstOrDefault()
mainWindow.Label.Content = progressStr
End Sub))
It is very bad practice to use anything global (shared/static). Use instance of class or other mechanism (Dependency Injection, messaging, events, etc.) for communication between independent classes.
The code below pulls out a bunch of records from an Access 2010 database; hence rolling my own connector bits. I've succeeded in doing the observablecollection and made it all bind up with nice drag and drop data sources, from my own objects. However, like a daft person, I want to do this Asynchronously. Yet, I've got a small cast monster problem, and I don't know what to feed it! Can anyone advise me - I've tried a lot of reading around, but the concepts are just a little too many at once on a Friday afternoon and I'm struggling to make any real headway.
The line I'm having trouble with is:
Dim dispatcherObject As DispatcherObject = CType (handler.Target, DispatcherObject )
The exception is:
Unable to cast object of type '_Closure$__2[SomeRecord_Viewer.SomeRecord]' to type 'System.Windows.Threading.DispatcherObject'.
I've managed to make a WPF listbox populate via the code below, however only by commenting out a part of the ObservableCollectionEx class. This causes synchronisation problems and a crash after a few hundred records are entered.
Class that builds the threaded list of entities - in this case, an ObservableCollectionEx(Of SomeRecord):
Class SomeRecordSet
Inherits ObservableCollectionEx( Of SomeRecord)
Private Shared Property _SomeRecordList As New ObservableCollectionEx(Of SomeRecord )
Public Shared ReadOnly Property SomeRecordList As ObservableCollectionEx(Of SomeRecord )
Get
If _SomeRecordList.Count = 0 Then BuildSomeRecordListAsync()
Return _SomeRecordList
End Get
End Property
Public Shared ReadOnly Property ReturnSingleSomeRecord(id As Integer) As SomeRecord
Get
Return ( From SomeRecord In _SomeRecordList Where SomeRecord.id = id Select SomeRecord).First()
End Get
End Property
Private Shared Async Sub BuildSomeRecordListAsync()
Await Task.Run( Sub() BuildSomeRecordList())
Return
End Sub
Private Shared Sub BuildSomeRecordList()
Db.newcmd( "Select * from RecordList ")
While Db.read
Dim SomeRecord As New SomeRecord
With SomeRecord
.id = Db.dbint( "ID")
.type = Db.dbin( "type")
End With
_SomeRecordList.Add(SomeRecord)
End While
End Sub`
Partial code for the SomeRecord class:
Class SomeRecord
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged( ByVal info As String)
RaiseEvent PropertyChanged(Me , New PropertyChangedEventArgs (info))
End Sub
...'lots of simple properties.
End Class
The threaded collection class code - translated from another online source.
'I use PostSharp for try catch stuff.
`
Public Class ObservableCollectionEx (Of T )
Inherits ObservableCollection( Of T)
' Override the event so this class can access it
Public Shadows Event CollectionChanged As System.Collections.Specialized.NotifyCollectionChangedEventHandler
Protected Overrides Sub OnCollectionChanged( ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs )
Using BlockReentrancy()
Dim eventHandler As System.Collections.Specialized.NotifyCollectionChangedEventHandler = Sub () RaiseEvent CollectionChanged(Me , e)
If (eventHandler Is Nothing) Then Return
Dim delegates() As [Delegate] = eventHandler.GetInvocationList
*******If I comment this out I can populate the Listbox via a CollectionView, however it dies with issues to do with the list not staying synchronised :).
'Walk thru invocation list
For Each handler As System.Collections.Specialized.NotifyCollectionChangedEventHandler In delegates
Dim dispatcherObject As DispatcherObject = CType (handler.Target, DispatcherObject)
' If the subscriber is a DispatcherObject and different thread
If (( Not (dispatcherObject) Is Nothing) AndAlso (dispatcherObject.CheckAccess = False )) Then
' Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority .DataBind, handler, Me, e)
Else
handler( Me, e)
End If
Next
*******End of stuff I comment out to get working partially***
End Using
End Sub
End Class
From what I can see, you have two problems.
You're assigning the local variable eventHandler to an anonymous method, rather than the actual event handler. It should be:
Dim eventHandler As NotifyCollectionChangedEventHandler = CollectionChangedEvent
NB: You need to use CollectionChangedEvent in VB, not CollectionChanged.
You're using CType to cast the target to a DispatcherObject, which won't work if the target isn't a DispatcherObject. Use TryCast instead:
Dim dispatcherObject As DispatcherObject = TryCast(handler.Target, DispatcherObject)
You can also tidy up the test on the next line by using IsNot:
If dispatcherObject IsNot Nothing AndAlso Not dispatcherObject.CheckAccess Then
WARNING - The code below acts differently to the C# version. The key difference seems to be that in VB you can't Override an Event (Why on earth not?) yet in C# you can.
The result is the Handler is Nothing in VB but not in C# :(.
So the syntax builds without error but the VB version doesn't ever do anything.
Redone with the updated answer in VB. Thank you!
Note I cannot make this work with Entity Framework, yet. But I think that a me and EF issue, not the collection.
The code itself is here for anyone interested. My list DOES populate perfectly fine now. However, I would take this answer of mine with a small pinch of salt until I update saying how I've extensively tested perhaps :)
However the omens are good - here is the original C# author's site: Original Site
Public Class ObservableCollectionEx(Of T)
Inherits ObservableCollection(Of T)
'Override the event so this class can access it
Public Shadows Event CollectionChanged As NotifyCollectionChangedEventHandler
Protected Overrides Sub OnCollectionChanged(ByVal e As NotifyCollectionChangedEventArgs)
Using BlockReentrancy()
Dim eventHandler As System.Collections.Specialized.NotifyCollectionChangedEventHandler = CollectionChangedEvent
If eventHandler Is Nothing Then
Return
End If
Dim delegates() As [Delegate] = CollectionChangedEvent.GetInvocationList
'Walk thru invocation list
For Each handler As NotifyCollectionChangedEventHandler In delegates
Dim dispatcherObject As DispatcherObject = TryCast(handler.Target, DispatcherObject)
' If the subscriber is a DispatcherObject and different thread
If dispatcherObject IsNot Nothing AndAlso Not dispatcherObject.CheckAccess Then
' Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, Me, e)
Else
handler(Me, e)
End If
Next
End Using
End Sub
End Class
Has anyone using VB.NET 2010 been able to create a single instance application?
I've followed the MSDN sample but it does not have an Application.xaml file.
Converting any C# samples to VB doesn't work as I cannot override the Main sub in Application.xaml (C# calls it App.xaml).
You can try using a Mutex. In the projects properties, disable the application framework and set Sub Main as the startup object. Then add a Module to your project:
Imports System.Threading
Module EntryPoint
Sub Main()
Dim noPreviousInstance As Boolean
Using m As New Mutex(True, "Some Unique Identifier String", noPreviousInstance)
If Not noPreviousInstance Then
MessageBox.Show("Application is already started!")
Else
Dim mainWindow As New MainWindow()
Dim app As New Application()
app.Run(mainWindow)
End If
End Using
End Sub
End Module
With this method, you will have to take care of your app's shutdown by calling the Shutdown method of the application.
Here's a few possible solutions. I'd look through the whole thread here before deciding on one. Make sure you backup your code before trying any of these, so if one doesn't work, you can try another.
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/6c15b837-9149-4b07-8a25-3266949621a7/